package org.ezplatform.office.calendar.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.umc.UmcApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.cloud.common.service.ConfigService;
import org.ezplatform.cloud.common.util.AuthUtils;
import org.ezplatform.component.message.client.dto.MessageBodyDTO;
import org.ezplatform.component.message.client.dto.SendMessageDTO;
import org.ezplatform.component.message.client.service.SendMessageApiService;
import org.ezplatform.component.message.client.util.ResourceTypes;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.integ.websocket.annotation.WebsocketCode;
import org.ezplatform.integ.websocket.constant.WebsocketConstant;
import org.ezplatform.integ.websocket.util.WebsocketUtils;
import org.ezplatform.mobile.menhu.util.AuthHelper;
import org.ezplatform.mobile.setting.service.MobileAppInfoService;
import org.ezplatform.office.api.client.oa.mail.MailApiService;
import org.ezplatform.office.api.client.oa.psc.group.PscGroupApiService;
import org.ezplatform.office.calendar.dao.*;
import org.ezplatform.office.calendar.entity.*;
import org.ezplatform.office.calendar.entity.Calendar;
import org.ezplatform.office.calendar.util.CalendarSecUtils;
import org.ezplatform.office.calendar.util.CalendarSendMsgUtils;
import org.ezplatform.office.calendar.util.CalendarUtils;
import org.ezplatform.office.calendar.util.HttpsUtil;
import org.ezplatform.sdk.AccessToken;
import org.ezplatform.sdk.Client;
import org.springframework.jdbc.core.JdbcTemplate;
import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("calendarService")
@Transactional
@Slf4j
public class CalendarService extends BaseService<Calendar, String> {
    private final static Logger LOG = LoggerFactory.getLogger(CalendarService.class);

    @Autowired
    @Qualifier("calendarDao")
    private CalendarDao calendarDao;

    private static String MODULETYPE = "calendar";

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CmpApplyScopeService cmpApplyScopeService;

    @Autowired
    private MobileAppInfoService mobileAppInfoService;

    @Autowired
    private CalendarCategoryDao calendarCategoryDao;

    @Autowired
    @Lazy
    private CalendarCategoryService calendarCategoryService;

    @Autowired
    private CalendarSendMsgUtils calendarSendMsgUtils;

    private RestClient restClient = new RestClient(false);

    private RestClient restBaseClient = new RestClient(true);

    @Autowired
    private PopUserScopeUtilService popUserScopeUtilService;

    @Autowired
    private CalendarDeleteDao calendarDeleteDao;

    @Autowired
    private CalendarFinishedDao calendarFinishedDao;

    @Autowired
    private CalendarSettingDao calendarSettingDao;

    @Autowired
    private CalendarThirdDao calendarThirdDao;

    @Autowired
    private UserApiService userApiService;

    @Autowired
    private OrgApiService orgApiService;

    @Autowired
    private LogService logService;

    @Autowired
    private CalendarLeaderSettingService calendarLeaderSettingService;

    @Autowired
    private CalendarLeaderCategoryService calendarLeaderCategoryService;

    @Autowired
    private CalendarSettingService calendarSettingService;

    @Autowired
    private SendMessageApiService sendMessageApiService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private CalendarDeleteService calendarDeleteService;

    @Autowired
    private AttachmentUtilsService attachmentUtilsService;

    @Autowired
    private CalendarCustomService calendarCustomService;

    @Autowired
    private CalendarThirdService calendarThirdService;

    @Autowired
    private UmcApiService umcApiService;

    @Autowired
    private MailApiService mailApiService;

    @Autowired
    private PscGroupApiService pscGroupApiService;


    private final static String[] WEEKS = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};


    @Override
    protected JpaBaseDao<Calendar, String> getEntityDao() {
        return this.calendarDao;
    }

    /**
     * 获取个人日程、系统日程或共享日程，月视图查询日程方法
     * @param userId
     * @param corpId
     * @param title  日程标题
     * @param category
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("unused")
    public String getOaCalendar(String sharedId, String userId, String corpId, String title, String category, String viewType, String start, String end, String token, String leader,WebUser user) throws ParseException{
        if (StringUtils.isNotEmpty(title)) {
            title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
        }
        List<Calendar> list = new ArrayList<Calendar>();
        Date startDate = null,endDate = null;
        List<String> maintainFieldValue = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){
            if(StringUtils.isEmpty(sharedId)) {//共享日程选择'全部选项'
                List<String> shareIdList = new ArrayList<>();
                //共享日程选择'全部'选项
                if(StringUtils.isEmpty(sharedId)) {
                    //查出所有共享人
                    List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                    for(Map<String, String> map : shareUserList) {
                        shareIdList.add(map.get("userId"));
                    }
                }
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);//共享日程
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);//共享分类
                    cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findAllSharedOaCalendar("%"+title+"%",shareIdList,shareCalFieldValue,cates,startDate,endDate,corpId);
                    maintainFieldValue = this.getAllMaintainFieldValue(userId,shareIdList,corpId,token);
                }
            }else {//共享日程选择某个"共享人"
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);//共享日程
                cates = new ArrayList<>();
                shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);//共享分类
                source = this.getSysSources(corpId);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
                if(!StringUtils.isEmpty(category)){
                    if(category.contains(",")){
                        list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId,category.split(","));
                    }else{
                        if(cates.contains(category)){
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,category,startDate,endDate,corpId);
                        }else{
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,category,startDate,endDate,corpId);
                        }
                    }
                }else{
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId);
                }
                maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    String[] categories = category.split(",");
                    if(ArrayUtils.contains(categories, cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    list = this.calendarDao.findCalendar("%"+title+"%", categories, partFieldValue, startDate, endDate, corpId, userId);
                }else{
                    if(category.equals(cate.getId())){
                        list = this.calendarDao.findPartCalendar("%"+title+"%",partFieldValue, startDate, endDate, corpId);
                    }else{
                        //获取当前用户的所有日程分类
                        List<CalendarCategory> categoriesSys = this.calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
                        if(categoriesSys != null && !categoriesSys.isEmpty()) {
                            CalendarCategory cat = this.calendarCategoryDao.getCategoryById(category,corpId);
                            //导出下属日程选了日程分类时
                            if(StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findSubByCategory("%"+title+"%",category, startDate, endDate, corpId);
                                //我的日程勾选了某一分类时
                            }else if(!StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findMineByCategory("%"+title+"%",category, startDate, endDate, corpId);
                            }
                        }
                    }
                }
            }else{
                List<String> sysCate = new ArrayList<>();
                if(StringUtils.isNotEmpty(leader)) {
                    sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
                }
                if(sysCate.isEmpty()){
                    sysCate.add("1");
                }
                //领导日程查询和定时提醒任务查询
                if("1".equals(leader) || StringUtils.equals("remind", leader)) {
                    if(StringUtils.equals("1", leader)) {
                        list = this.calendarDao.findMineOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                        if(CollectionUtils.isNotEmpty(partFieldValue)) {
                            List<Calendar> partList = this.calendarDao.findMinePartOaCalendar("%"+title+"%", partFieldValue, startDate, endDate, corpId, sysCate);
                            if(CollectionUtils.isNotEmpty(partList)) {
                                for(Calendar ca : partList) {
                                    //给参与日程id装进calendarIdList里
                                    Calendar newCalendar = new Calendar();
                                    BeanUtils.copyProperties(ca, newCalendar);
                                    super.detach(newCalendar);
                                    newCalendar.setCalendarCategory(newCalendar.getCalendarCategory()+"_part");
                                    list.add(newCalendar);
                                }
                            }
                        }
                    }else {
                        list = this.calendarDao.findRemindOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                    }
                }else {
                    LOG.debug("查询开始:title:"+title+",userId:"+userId+",partFieldValue:"+partFieldValue+",startDate:"+startDate+",endDate:"+endDate+",corpId:"+corpId+",sysCate:"+sysCate);
                    list = this.calendarDao.findMineOaCalendar("%"+title+"%",userId, partFieldValue, startDate, endDate, corpId, sysCate);
                }
            }
        }
        StringBuffer json = new StringBuffer();
        json.append("[");
        if(list!=null && !list.isEmpty()){
            String isComplateId = sharedId;
            String complateType = "1";
            if(StringUtils.equals(viewType, "share")) {
                if(StringUtils.equals(sharedId, "") && StringUtils.equals(leader, "1")) {
                    complateType = "2";
                }else {
                    complateType = "3";
                }
            }
            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            List<String> calendarCategorys = new ArrayList<String>();
            String calendarCategoryFlag = "";
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                String calendarId = calendar.getId();
                String calendarCategory = calendar.getCalendarCategory();
                calendarIds.add(calendarId);
                if(!StringUtils.equals(calendarCategoryFlag, calendarCategory)) {
                    calendarCategorys.add(calendarCategory);
                    calendarCategoryFlag = calendarCategory;
                }
            }
            List<CalendarDelete> deletes = new ArrayList<>();
            deletes = this.calendarDeleteDao.findByBelongs(calendarIds, CalendarUtils.getDataByStr(end, "yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deletes) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }
            //----end----
            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryByIds(calendarCategorys, corpId);
            Map<String,CalendarCategory> categorysMap = new HashMap<String,CalendarCategory>();
            for (CalendarCategory calendarCategory : categorys) {
                categorysMap.put(calendarCategory.getId(), calendarCategory);
            }
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeats = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeats) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }

            //领导日程的遗留修补
            if("1".equals(leader)){
                viewType = "share";
            }

            /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
            List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
            Map<String,List<String>> partFinishedMap = new HashMap<>();
            for(String calendarId : calendarIds){
                List<String> partIdList = new ArrayList<>();
                for(CalendarFinished calendarFinished : calendarFinishedList){
                    if(calendarId.equals(calendarFinished.getCalendarId())){
                        partIdList.add(calendarFinished.getPartId());
                    }
                }
                partFinishedMap.put(calendarId,partIdList);
            }


            //---end----
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                if(calendar != null){
                    calendar = this.encodeCalendar(calendar,user.getUserId());
                    String jsonString = this.getCalendarInfo(complateType,isComplateId,calendar,start,end,viewType,userId,corpId,maintainFieldValue,deletesMap,categorysMap,repeatsMap,partFinishedMap);
                    if(StringUtils.isNotBlank(jsonString)) {
                        json.append(jsonString);
                        if(i != list.size()-1){
                            json.append(",");
                        }
                    }
                }
            }
        }
        return json.append("]").toString();
    }



    /**
     * 进行中/已完成日程查询
     * @param sharedId
     * @param userId
     * @param corpId
     * @param title
     * @param category
     * @param viewType
     * @param start
     * @param end
     * @param token
     * @param leader
     * @param ingOrFinish
     * @return
     * @throws ParseException
     */
    public String getOaCalendar(String sharedId, String userId, String corpId, String title, String category, String viewType, String start, String end, String token, String leader, String ingOrFinish) throws ParseException{
        if (StringUtils.isNotEmpty(title)) {
            title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
        }
        WebUser user = WebUtils.getCurrentUser();
        //获取当前用户的参与日程和拥有日程
        List<CalendarCategory> categoriesSys= this.calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
        List<Calendar> list = new ArrayList<Calendar>();
        Date startDate = null,endDate = null;
        List<String> maintainFieldValue = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){//带是否完成参数的，只有我的日程
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    String[] categories = category.split(",");
                    if(ArrayUtils.contains(categories, cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    list = this.calendarDao.findCalendar("%"+title+"%", categories, partFieldValue, startDate, endDate, corpId, userId);
                }else{
                    if(category.equals(cate.getId())){
                        list = this.calendarDao.findPartCalendar("%"+title+"%",partFieldValue, startDate, endDate, corpId);
                    }else{
                        if(categoriesSys != null && !categoriesSys.isEmpty()) {
                            CalendarCategory cat = this.calendarCategoryDao.getSysCategory(corpId,category,userId);
                            //导出下属日程选了日程分类时
                            if(StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findSubByCategory("%"+title+"%",category, startDate, endDate, corpId);
                                //我的日程勾选了某一分类时
                            }else if(!StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findMineByCategory("%"+title+"%",category, startDate, endDate, corpId);
                            }
                        }
                    }
                }
            }else{
                List<String> sysCate = new ArrayList<>();
                if(StringUtils.isNotEmpty(leader)) {
                    sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
                }
                if(sysCate.isEmpty()){
                    sysCate.add("1");
                }
                //领导日程查询和定时提醒任务查询
                if("1".equals(leader) || StringUtils.equals("remind", leader)) {
                    if(StringUtils.equals("1", leader)) {
                        list = this.calendarDao.findMineOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                        if(CollectionUtils.isNotEmpty(partFieldValue)) {
                            List<Calendar> partList = this.calendarDao.findMinePartOaCalendar("%"+title+"%", partFieldValue, startDate, endDate, corpId, sysCate);
                            if(CollectionUtils.isNotEmpty(partList)) {
                                for(Calendar ca : partList) {
                                    //给参与日程id装进calendarIdList里
                                    Calendar newCalendar = new Calendar();
                                    BeanUtils.copyProperties(ca, newCalendar);
                                    super.detach(newCalendar);
                                    newCalendar.setCalendarCategory(newCalendar.getCalendarCategory()+"_part");
                                    list.add(newCalendar);
                                }
                            }
                        }
                    }else {
                        list = this.calendarDao.findRemindOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                    }
                }else {
                    LOG.debug("查询开始:title:"+title+",userId:"+userId+",partFieldValue:"+partFieldValue+",startDate:"+startDate+",endDate:"+endDate+",corpId:"+corpId+",sysCate:"+sysCate);
                    list = this.calendarDao.findMineOaCalendar("%"+title+"%",userId, partFieldValue, startDate, endDate, corpId, sysCate);
                }
            }
        }
        StringBuffer json = new StringBuffer();
        json.append("[");
        if(list!=null && !list.isEmpty()){
            String isComplateId = sharedId;
            String complateType = "1";
            if(StringUtils.equals(viewType, "share")) {
                if(StringUtils.equals(sharedId, "") && StringUtils.equals(leader, "1")) {
                    complateType = "2";
                }else {
                    complateType = "3";
                }
            }

            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            List<String> calendarCategorys = new ArrayList<String>();
            String calendarCategoryFlag = "";
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                String calendarId = calendar.getId();
                String calendarCategory = calendar.getCalendarCategory();
                calendarIds.add(calendarId);
                if(!StringUtils.equals(calendarCategoryFlag, calendarCategory)) {
                    calendarCategorys.add(calendarCategory);
                    calendarCategoryFlag = calendarCategory;
                }
            }
            List<CalendarDelete> deletes = new ArrayList<>();
            deletes = this.calendarDeleteDao.findByBelongs(calendarIds, CalendarUtils.getDataByStr(end, "yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deletes) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }

            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryByIds(calendarCategorys, corpId);
            Map<String,CalendarCategory> categorysMap = new HashMap<String,CalendarCategory>();
            for (CalendarCategory calendarCategory : categorys) {
                categorysMap.put(calendarCategory.getId(), calendarCategory);
            }
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeats = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeats) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }

            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                // 20210830 日程标记完成功能：判断当前用户是否是日程创建者，如果当前用户是日程创建者，则完成状态不需要处理，否则需要对完成状态进行处理 start
                if (!userId.equals(calendar.getCreatedBy())){
                    // 当前用户非日程创建者（日程参与者），查询当前日程参与者是否完成日程
                    List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedByCalendarIdAndPartId(calendar.getId(), userId);
                    if (CollectionUtils.isEmpty(calendarFinishedList) || calendarFinishedList.size()<1) {
                        // 为空：日程参与者未标记完成
                        calendar.setIsComplate(null);
                    } else {
                        // 不为空：日程参与者标记完成
                        calendar.setIsComplate("1");
                    }
                }

                /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
                List<CalendarFinished> allCalendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
                Map<String,List<String>> partFinishedMap = new HashMap<>();
                for(String calendarId : calendarIds){
                    List<String> partIdList = new ArrayList<>();
                    for(CalendarFinished calendarFinished : allCalendarFinishedList){
                        if(calendarId.equals(calendarFinished.getCalendarId())){
                            partIdList.add(calendarFinished.getPartId());
                        }
                    }
                    partFinishedMap.put(calendarId,partIdList);
                }

                // 20210830 日程标记完成功能：判断当前用户是否是日程创建者，如果当前用户是日程创建者，则完成状态不需要处理，否则需要对完成状态进行处理 end
                if(calendar != null){
                    calendar = this.encodeCalendar(calendar,user.getUserId());
                    String jsonString = this.getCalendarInfo(complateType,isComplateId,calendar,start,end,viewType,userId,corpId,maintainFieldValue,deletesMap,categorysMap,repeatsMap,ingOrFinish,partFinishedMap);
                    if(StringUtils.isNotBlank(jsonString)) {
                        json.append(jsonString);
                        if(i != list.size()-1){
                            json.append(",");
                        }
                    }

                }
            }
        }
        return json.append("]").toString();
    }


    /**
     * 获取个人日程、系统日程或共享日程，月视图查询日程方法
     * @param userId
     * @param corpId
     * @param title
     * @param category
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("unused")
    public String getOaCalendarWithoutLeader(String sharedId, String userId, String corpId, String title, String category, String viewType, String start, String end, String token, String leader,String selectViewType) throws ParseException{
        if (StringUtils.isNotEmpty(title)) {
            title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
        }
        //获取当前用户的参与日程和拥有日程
        List<CalendarCategory> categoriesSys= this.calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
        List<Calendar> list = new ArrayList<Calendar>();
        Date startDate = null,endDate = null;
        List<String> maintainFieldValue = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){
            if(StringUtils.isEmpty(sharedId)) {//共享日程选择'全部选项'
                List<String> shareIdList = new ArrayList<>();
                //共享日程选择'全部'选项
                if(StringUtils.isEmpty(sharedId)) {
                    //查出所有共享人
                    List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                    for(Map<String, String> map : shareUserList) {
                        shareIdList.add(map.get("userId"));
                    }
                }
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);//共享日程
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);//共享分类
                    cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findAllSharedOaCalendar("%"+title+"%",shareIdList,shareCalFieldValue,cates,startDate,endDate,corpId);
                    maintainFieldValue = this.getAllMaintainFieldValue(userId,shareIdList,corpId,token);
                }
            }else {//共享日程选择某个"共享人"
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);//共享日程
                cates = new ArrayList<>();
                shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);//共享分类
                source = this.getSysSources(corpId);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
                if(!StringUtils.isEmpty(category)){
                    if(category.contains(",")){
                        list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId,category.split(","));
                    }else{
                        if(cates.contains(category)){
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,category,startDate,endDate,corpId);
                        }else{
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,category,startDate,endDate,corpId);
                        }
                    }
                }else{
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId);
                }
                maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    String[] categories = category.split(",");
                    if(ArrayUtils.contains(categories, cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    list = this.calendarDao.findCalendar("%"+title+"%", categories, partFieldValue, startDate, endDate, corpId, userId);
                }else{
                    if(category.equals(cate.getId())){
                        list = this.calendarDao.findPartCalendar("%"+title+"%",partFieldValue, startDate, endDate, corpId);
                    }else{
                        if(categoriesSys != null && !categoriesSys.isEmpty()) {
                            CalendarCategory cat = this.calendarCategoryDao.getSysCategory(corpId,category,userId);
                            //导出下属日程选了日程分类时
                            if(StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findSubByCategory("%"+title+"%",category, startDate, endDate, corpId);
                                //我的日程勾选了某一分类时
                            }else if(!StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findMineByCategory("%"+title+"%",category, startDate, endDate, corpId);
                            }
                        }
                    }
                }
            }else{
                List<String> sysCate = new ArrayList<>();
                if(StringUtils.isNotEmpty(leader)) {
                    sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
                }
                if(sysCate.isEmpty()){
                    sysCate.add("1");
                }
                //领导日程查询和定时提醒任务查询
                // 2022-01-21 去除下属日程

                if(("1".equals(leader) || StringUtils.equals("remind", leader))) {
                    if(StringUtils.equals("1", leader)) {
                        list = this.calendarDao.findMineOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
//                        if(!"subCalendar".equals(selectViewType)){
                            if(CollectionUtils.isNotEmpty(partFieldValue)) {
                                List<Calendar> partList = this.calendarDao.findMinePartOaCalendar("%"+title+"%", partFieldValue, startDate, endDate, corpId, sysCate);
                                if(CollectionUtils.isNotEmpty(partList)) {
                                    for(Calendar ca : partList) {
                                        //给参与日程id装进calendarIdList里
                                        Calendar newCalendar = new Calendar();
                                        BeanUtils.copyProperties(ca, newCalendar);
                                        super.detach(newCalendar);
                                        newCalendar.setCalendarCategory(newCalendar.getCalendarCategory()+"_part");
                                        list.add(newCalendar);
                                    }
                                }
                            }
//                        }
                    }else {
                        list = this.calendarDao.findRemindOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                    }
                }else {
                    LOG.debug("查询开始:title:"+title+",userId:"+userId+",partFieldValue:"+partFieldValue+",startDate:"+startDate+",endDate:"+endDate+",corpId:"+corpId+",sysCate:"+sysCate);
                    list = this.calendarDao.findMineOaCalendar("%"+title+"%",userId, partFieldValue, startDate, endDate, corpId, sysCate);
                }


            }
        }
        StringBuffer json = new StringBuffer();
        json.append("[");
        if(list!=null && !list.isEmpty()){
            String isComplateId = sharedId;
            String complateType = "1";
            if(StringUtils.equals(viewType, "share")) {
                if(StringUtils.equals(sharedId, "") && StringUtils.equals(leader, "1")) {
                    complateType = "2";
                }else {
                    complateType = "3";
                }
            }
            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            List<String> calendarCategorys = new ArrayList<String>();
            String calendarCategoryFlag = "";
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                String calendarId = calendar.getId();
                String calendarCategory = calendar.getCalendarCategory();
                calendarIds.add(calendarId);
                if(!StringUtils.equals(calendarCategoryFlag, calendarCategory)) {
                    calendarCategorys.add(calendarCategory);
                    calendarCategoryFlag = calendarCategory;
                }
            }
            List<CalendarDelete> deletes = new ArrayList<>();
            deletes = this.calendarDeleteDao.findByBelongs(calendarIds, CalendarUtils.getDataByStr(end, "yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deletes) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }
            //----end----
            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryByIds(calendarCategorys, corpId);
            Map<String,CalendarCategory> categorysMap = new HashMap<String,CalendarCategory>();
            for (CalendarCategory calendarCategory : categorys) {
                categorysMap.put(calendarCategory.getId(), calendarCategory);
            }
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeats = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeats) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }

            /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
            List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
            Map<String,List<String>> partFinishedMap = new HashMap<>();
            for(String calendarId : calendarIds){
                List<String> partIdList = new ArrayList<>();
                for(CalendarFinished calendarFinished : calendarFinishedList){
                    if(calendarId.equals(calendarFinished.getCalendarId())){
                        partIdList.add(calendarFinished.getPartId());
                    }
                }
                partFinishedMap.put(calendarId,partIdList);
            }

            //---end----
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                if(calendar != null){
                    String jsonString = this.getCalendarInfo(complateType,isComplateId,calendar,start,end,viewType,userId,corpId,maintainFieldValue,deletesMap,categorysMap,repeatsMap,partFinishedMap);
                    if(StringUtils.isNotBlank(jsonString)) {
                        json.append(jsonString);
                        if(i != list.size()-1){
                            json.append(",");
                        }
                    }
                }
            }
        }
        return json.append("]").toString();
    }

    public String getOaCalendarForLeader(String sharedId, String userId, String corpId, String title, String category, String viewType, String start, String end, String token, String leader, WebUser user) throws ParseException {
        if (StringUtils.isNotEmpty(title)) {
            title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
        }

        //获取当前用户的参与日程和拥有日程
        List<CalendarCategory> categoriesSys= this.calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
        List<Calendar> list = new ArrayList<Calendar>();
        Date startDate = null,endDate = null;
        List<String> maintainFieldValue = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){
            if(StringUtils.isEmpty(sharedId)) {//共享日程选择'全部选项'
                List<String> shareIdList = new ArrayList<>();
                //共享日程选择'全部'选项
                if(StringUtils.isEmpty(sharedId)) {
                    //查出所有共享人
                    List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                    for(Map<String, String> map : shareUserList) {
                        shareIdList.add(map.get("userId"));
                    }
                }
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);//共享日程
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);//共享分类
                    cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findAllSharedOaCalendar("%"+title+"%",shareIdList,shareCalFieldValue,cates,startDate,endDate,corpId);
                    maintainFieldValue = this.getAllMaintainFieldValue(userId,shareIdList,corpId,token);
                }
            }else {//共享日程选择某个"共享人"
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);//共享日程
                cates = new ArrayList<>();
                shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);//共享分类
                source = this.getSysSources(corpId);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
                if(!StringUtils.isEmpty(category)){
                    if(category.contains(",")){
                        list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId,category.split(","));
                    }else{
                        if(cates.contains(category)){
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,category,startDate,endDate,corpId);
                        }else{
                            list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,category,startDate,endDate,corpId);
                        }
                    }
                }else{
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findSharedOaCalendar("%"+title+"%",sharedId,shareCalFieldValue,cates,startDate,endDate,corpId);
                }
                maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    String[] categories = category.split(",");
                    if(ArrayUtils.contains(categories, cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    list = this.calendarDao.findCalendar("%"+title+"%", categories, partFieldValue, startDate, endDate, corpId, userId);
                }else{
                    if(category.equals(cate.getId())){
                        list = this.calendarDao.findPartCalendar("%"+title+"%",partFieldValue, startDate, endDate, corpId);
                    }else{
                        if(categoriesSys != null && !categoriesSys.isEmpty()) {
                            CalendarCategory cat = this.calendarCategoryDao.getSysCategory(corpId,category,userId);
                            //导出下属日程选了日程分类时
                            if(StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findSubByCategory("%"+title+"%",category, startDate, endDate, corpId);
                                //我的日程勾选了某一分类时
                            }else if(!StringUtils.equals("1", leader) && cat != null) {
                                list = this.calendarDao.findMineByCategory("%"+title+"%",category, startDate, endDate, corpId);
                            }
                        }
                    }
                }
            }else{
                List<String> sysCate = new ArrayList<>();
                if(StringUtils.isNotEmpty(leader)) {
                    sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
                }
                if(sysCate.isEmpty()){
                    sysCate.add("1");
                }
                //领导日程查询和定时提醒任务查询
                if("1".equals(leader) || StringUtils.equals("remind", leader)) {
                    if(StringUtils.equals("1", leader)) {
                        list = this.calendarDao.findMineOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                        if(CollectionUtils.isNotEmpty(partFieldValue)) {
                            List<Calendar> partList = this.calendarDao.findMinePartOaCalendar("%"+title+"%", partFieldValue, startDate, endDate, corpId, sysCate);
                            if(CollectionUtils.isNotEmpty(partList)) {
                                for(Calendar ca : partList) {
                                    //给参与日程id装进calendarIdList里
                                    Calendar newCalendar = new Calendar();
                                    BeanUtils.copyProperties(ca, newCalendar);
                                    super.detach(newCalendar);
                                    newCalendar.setCalendarCategory(newCalendar.getCalendarCategory()+"_part");
                                    list.add(newCalendar);
                                }
                            }
                        }
                    }else {
                        list = this.calendarDao.findRemindOaCalendarNoSys("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                    }
                }else {
                    LOG.debug("查询开始:title:"+title+",userId:"+userId+",partFieldValue:"+partFieldValue+",startDate:"+startDate+",endDate:"+endDate+",corpId:"+corpId+",sysCate:"+sysCate);
                    list = this.calendarDao.findMineOaCalendar("%"+title+"%",userId, partFieldValue, startDate, endDate, corpId, sysCate);
                }
            }
        }
        StringBuffer json = new StringBuffer();
        json.append("[");
        if(list!=null && !list.isEmpty()){
            String isComplateId = sharedId;
            String complateType = "1";
            if(StringUtils.equals(viewType, "share")) {
                if(StringUtils.equals(sharedId, "") && StringUtils.equals(leader, "1")) {
                    complateType = "2";
                }else {
                    complateType = "3";
                }
            }
            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            List<String> calendarCategorys = new ArrayList<String>();
            String calendarCategoryFlag = "";
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                String calendarId = calendar.getId();
                String calendarCategory = calendar.getCalendarCategory();
                calendarIds.add(calendarId);
                if(!StringUtils.equals(calendarCategoryFlag, calendarCategory)) {
                    calendarCategorys.add(calendarCategory);
                    calendarCategoryFlag = calendarCategory;
                }
            }
            List<CalendarDelete> deletes = new ArrayList<>();
            deletes = this.calendarDeleteDao.findByBelongs(calendarIds, CalendarUtils.getDataByStr(end, "yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deletes) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }
            //----end----
            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryByIds(calendarCategorys, corpId);
            Map<String,CalendarCategory> categorysMap = new HashMap<String,CalendarCategory>();
            for (CalendarCategory calendarCategory : categorys) {
                categorysMap.put(calendarCategory.getId(), calendarCategory);
            }
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeats = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeats) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }

            /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
            List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
            Map<String,List<String>> partFinishedMap = new HashMap<>();
            for(String calendarId : calendarIds){
                List<String> partIdList = new ArrayList<>();
                for(CalendarFinished calendarFinished : calendarFinishedList){
                    if(calendarId.equals(calendarFinished.getCalendarId())){
                        partIdList.add(calendarFinished.getPartId());
                    }
                }
                partFinishedMap.put(calendarId,partIdList);
            }

            //---end----
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);

                if(calendar != null){
                    calendar = this.encodeCalendar(calendar,user.getUserId());
                    String jsonString = this.getCalendarInfoForLeader(complateType,isComplateId,calendar,start,end,viewType,userId,corpId,maintainFieldValue,deletesMap,categorysMap,repeatsMap,token,partFinishedMap);
                    if(StringUtils.isNotBlank(jsonString)) {
                        json.append(jsonString);
                        if(i != list.size()-1){
                            json.append(",");
                        }
                    }
                }
            }
        }
        return json.append("]").toString();
    }

    /**
     * 日程实体类id加密
     *
     *
     */
    public Calendar encodeCalendar(Calendar calendar,String userId){
        Map map = new HashMap();
        map.put("id",calendar.getId());
        map.put("userId",userId);
        Map<String,String> encodeMap = DealFieldEncodeUtils.dealDataMap(map,"id,userId","calendar",null);
        calendar.setSecdatacode(encodeMap.get("secdatacode"));
        return calendar;
    }

    public String getCalendarInfoForLeader(String complateType , String isComplateId ,Calendar calendar,String searchStart,String searchEnd,String viewType,String userId,String corpId,List<String> maintainFieldValue,Map<String,List<CalendarDelete>> deletesMap,Map<String,CalendarCategory> categoryMap,Map<String,List<Calendar>> repeatsMap,String token,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();
        String calendarStart = CalendarUtils.getStrByDate(calendar.getStartDate(), "yyyy-MM-dd");
        String calendarEnd = calendar.getEndDate()==null ? calendarStart : CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
        //拼接日程事件
        String isMain = calendar.getIsMain();

        String duplicateType = calendar.getDuplicateType();
        if(!"no".equals(duplicateType) && "1".equals(isMain)){//主日程拼接重复日程json
            Date startCalendarDate = DateUtils.parseDate(calendarStart);
            Date endCalendarDate = DateUtils.parseDate(calendarEnd);
            Date startSearchDate = DateUtils.parseDate(searchStart);
            Date startEndDate = DateUtils.parseDate(searchEnd);
            if((startCalendarDate.getTime()<=startSearchDate.getTime() && endCalendarDate.getTime()>=startSearchDate.getTime())
                    || (startCalendarDate.getTime()>=startSearchDate.getTime()&&startCalendarDate.getTime()<=startEndDate.getTime())){
                result.append(this.setCalendarJsonForLeader(complateType,isComplateId,calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,categoryMap,token,partFinishedMap));
            }

            String duplicateTypeValue = calendar.getDuplicateInterval();//重复间隔值
            String duplicateEndType = calendar.getDuplicateEndType();//重复结束类型
            String duplicateEndTypeValue = calendar.getDuplicateEndTypeValue();//重复结束类型值
            String weekMonthDuplicateType = calendar.getWeekMonthDuplicateType();//周/月重复类型
            List<Map<String, String>> list ;
            list = this.getDataMsg(duplicateType, duplicateTypeValue, duplicateEndType, duplicateEndTypeValue, calendarStart, calendarEnd==""?calendarStart:calendarEnd, searchEnd,weekMonthDuplicateType);

            if(list != null && !list.isEmpty()){
                String startDate = "";
                List<CalendarDelete> deletes = deletesMap.get(calendar.getId());
                //deletes = this.calendarDeleteDao.findByBelong(calendar.getId(), end);
                int flag = 0,flag1 = 0,flag2 = 0;
                String delFlag = "";
                for(int i=0;i<list.size();i++){
                    Map<String, String> map = list.get(i);
                    startDate = map.get("startDate");
                    if(deletes!=null && !deletes.isEmpty()){
                        for(int j=0;j<deletes.size();j++){
                            CalendarDelete delete = deletes.get(j);
                            if(delete != null){
                                delFlag = delete.getDeleteType();
                                if("current".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }else if("after".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }
                                if(flag == 0){
                                    break;
                                }
                            }
                        }
                        if(flag==0 && "current".equals(delFlag)){
                            continue;
                        }else if(flag==0 && "after".equals(delFlag)){
                            break;
                        }
                    }
                    flag1 = CalendarUtils.compareDateStr(searchStart, startDate);
                    flag = CalendarUtils.compareDateStr(searchEnd, startDate);
                    if(flag1!=1 && flag!=2){
                        List<Calendar> repeats = new ArrayList<>();
                        //repeats = this.calendarDao.findCalendarByBelong(calendar.getId(), start, end);
                        repeats = repeatsMap.get(calendar.getId());
                        boolean equal = true;
                        if(repeats!=null && !repeats.isEmpty()){
                            for(int j=0;j<repeats.size();j++){
                                Calendar repeat = repeats.get(j);
                                flag2 = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                if(flag2 == 0){
                                    equal = false;
                                    break;
                                }
                            }
                        }
                        if(equal){
                            result.append(",");
                            result.append(this.setCalendarJsonForLeader(complateType,isComplateId, calendar, startDate, map.get("endDate"),"repeat",viewType,userId,corpId,maintainFieldValue,categoryMap,token,partFinishedMap));
                        }
                    }
                }
            }
        }else{
            result.append(this.setCalendarJsonForLeader(complateType,isComplateId,calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,categoryMap,token,partFinishedMap));
        }
        return result.toString();
    }

    private String setCalendarJsonForLeader(String complateType, String isComplateId,Calendar calendar, String startDate, String endDate,String repeatType,String viewType,String userId,String corpId,List<String> maintainFieldValue,Map<String,CalendarCategory> categorysMap,String token,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();
        //查询当前用户是否已经完成该日程,如果complateType为4是不需要查询完成状况
        boolean isComplate = false;
        if(!StringUtils.equals(complateType, "4")) {
            // 指定日程标记完成参与人ID集合
//            List<String> partIdList = calendarFinishedDao.findPartId(calendar.getId());
            List<String> partIdList = partFinishedMap.get(calendar.getId());
            // 20210830 日程标记功能：判断当前用户是否标记完成日程
            // 共享日程判断日程是否完成判断的是创建人是否完成
            if (null != partIdList && partIdList.size() > 0) {
                if (partIdList.contains(calendar.getCalendarOwner())) {
                    isComplate = true;
                }
            }
//            if ("share".equals(viewType)) {
//                // 共享日程判断日程是否完成判断的是创建人是否完成
//                if (null != partIdList && partIdList.size() > 0) {
//                    if (partIdList.contains(calendar.getCalendarOwner())) {
//                        isComplate = true;
//                    }
//                }
//            } else {
//                if (null != partIdList && partIdList.size() > 0) {
//
//                    if (partIdList.contains(userId) ||
//                            (partIdList.contains(calendar.getCalendarOwner())&&userId.contains(calendar.getCalendarOwner()))) {
//                        isComplate = true;
//                    }
//                }
//            }
            // isComplate = StringUtils.equals("1", calendar.getIsComplate())?true:false;
            if(StringUtils.isNotEmpty(calendar.getStartDate().toString())) {
                String calendarStart = DateUtils.formatDate(calendar.getStartDate(),"yyyy-MM-dd");
                if(!StringUtils.equals(calendarStart, startDate)) {
                    isComplate = false;
                }
            }
        }

        boolean isRealCreator = StringUtils.equals(StringUtils.null2String(calendar.getCreatedBy()), userId);
        //获取领导名称
        Map<String,Object> userMap = this.userApiService.getUser( calendar.getCalendarOwner(), corpId, "", token);
        String userName = userMap==null || userMap.get("userName")==null ? "" : userMap.get("userName").toString()+"-";

        result.append("{mainId:'" + calendar.getId() + "'," +
                "secdatacode:'"+calendar.getSecdatacode()+"' ,"
                + "title:'" +userName+ calendar.getTitle().replace("\\","\\\\").replace("'","\\'").replace("[","flexbracketB").replace("[","flexbracketE")+ "',"
//                    + "title:'" +URLEncoder.encode(userName+ calendar.getTitle(),"utf-8")+ "',"
                + "isMain:'" + calendar.getIsMain() + "',"
                + "calendarOwner:'" + calendar.getCalendarOwner() + "',"
                + "isComplate:'" + isComplate + "',"
                + "content:'" + (calendar.getContent() == null ? "" : calendar.getContent().replace("\\","\\\\").replace("'","\\'")).replace("[","flexbracketB").replace("[","flexbracketE") + "',"
                + "isRealCreator:'" + isRealCreator + "'," //是否是日程创建人
                + "address:'" + (calendar.getAddress() == null ? "" : calendar.getAddress().replace("\\","\\\\").replace("'","\\'")).replace("[","flexbracketB").replace("[","flexbracketE") + "',"
                + "isDuplicate:'" + calendar.getDuplicateType() + "',"
                + "participant2:'" + calendar.getParticipant() + "',"
                + "realTitle:'"+ calendar.getTitle().replace("\\","\\\\").replace("'","\\'").replace("[","flexbracketB").replace("[","flexbracketE")+"',");

        if("1".equals(calendar.getIsAllDay())){//全天日程
            result.append("allDay:true,"
                    + "start:'" + startDate + "',"
                    + "startTime:'"+ 0 +"'," // 全天日程开始时间设置为0，显示在上午区域中
                    + "startWeek: '" + 0 +"',"  // 全天日程开始时间设置为0，标题前不显示时间
                    + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm: '"+ 1 +"',"); // 全天日程默认显示在上午
        } else if (StringUtils.isNotBlank(calendar.getSetTimeFlag())) { // 上午/下午模式
            String startTime = "";
            String endTime = "";
            int startTimeIntVal=0;
            int endTimeIntVal=0;
            if("1".equals(calendar.getSetTimeFlag())){
                startTime="09:00";
                startTimeIntVal=32400;
                endTime = "12:00";
                endTimeIntVal=43200;
            }else{
                startTime="14:00";
                startTimeIntVal=50400;
                endTime = "18:00";
                endTimeIntVal=64800;
            }
            result.append("allDay:false,"
                    + "start:'" + startDate + "T" + startTime + "',"
                    + "end:'" + endDate + "T" + endTime + "',"
                    + "startTime:'"+ startTimeIntVal +"'," // 全天日程开始时间设置为0，显示在上午区域中
                    + "endTime:'"+ endTimeIntVal +"'," //
                    + "startWeek: '" + 0 +"',"  // 上午/下午模式日程开始时间设置为0，标题前不显示时间
                    + "amOrPm:'" + 1 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm: '"+ (Integer.parseInt(calendar.getSetTimeFlag())<=0? "0":"1") +"',"); // 上午/下午模式中日程所处位置
        } else{
            String startTime = CalendarUtils.getTime(calendar.getStartTime());
            String endTime = CalendarUtils.getTime(calendar.getEndTime());
            result.append("allDay:false,start:'" + startDate + "T" + startTime + "',"
                    + "end:'" + endDate + "T" + endTime + "',"
                    + "startTime:'"+ calendar.getStartTime() +"',"
                    + "startWeek: '" + startDate + " " + startTime + "'," // 日程开始时间，用于标题前显示
                    + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm:'"+(Integer.parseInt(startTime.split(":")[0]) >= 12? "0": "1")+"',");
        }
        if("repeat".equals(repeatType) || "0".equals(calendar.getIsMain())){
            result.append("repeat:'1',");
            if("1".equals(calendar.getIsMain())){
                result.append("id:'" + calendar.getId() + "',");
            }else{
                result.append("id:'" + calendar.getBelongCalendar() + "',");
            }
            result.append("dragable:false,");
        }else{
            result.append("repeat:'0',").append("id:'" + calendar.getId() + "',");
        }
        CalendarCategory category = new CalendarCategory();
        if(StringUtils.null2String(calendar.getCalendarCategory()).contains("_part")) {//参与日程
            List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
            if (CollectionUtils.isNotEmpty(categorys)) {
                category = categorys.get(0);
            }
            super.detach(calendar);
            calendar.setCalendarCategory(calendar.getCalendarCategory().split("_")[0]);
            result.append("isPart:'1',");
        }else {
            if(!Arrays.asList(userId.split(",")).contains(calendar.getCalendarOwner()) && !"share".equals(viewType)){//参与日程
                List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
                if (CollectionUtils.isNotEmpty(categorys)) {
                    category = categorys.get(0);
                }
                result.append("isPart:'1',");
            }else{
                //category = this.calendarCategoryDao.getCategoryById(calendar.getCalendarCategory(), corpId);
                category = categorysMap.get(calendar.getCalendarCategory());
            }
        }
        if(category == null) {
            return "";
        }
        if("share".equals(viewType)){
            String fieldValue1 = StringUtils.null2String(calendar.getMaintainer());
            String fieldValue2 = StringUtils.null2String(category.getMaintainer());
            if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2))){
                result.append("isMaintain:'1',");
                if("repeat".equals(repeatType)){
                    if("1".equals(calendar.getIsMain())){
                        result.append("showEditMsg:'1',");
                    }else{
                        Calendar main = this.calendarDao.findById(calendar.getBelongCalendar()).get();
                        CalendarCategory cate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                        fieldValue1 = StringUtils.null2String(main.getMaintainer());
                        fieldValue2 = StringUtils.null2String(cate.getMaintainer());
                        if(maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2)){
                            result.append("showEditMsg:'1',");
                        }
                    }
                }
            }else{
                result.append("isMaintain:'0',");
                if(!"repeat".equals(viewType) && "1".equals(calendar.getIsMain())){
                    result.append("dragable:false,");
                }
            }
        }
        if("-1".equals(calendar.getIsMain())) {
            result.append("isMaintain:'-1',");
        }else if("-2".equals(calendar.getIsMain())) {
            result.append("isMaintain:'-2',");
        }
        result.append("classfiy:'" + category.getId() + "',");
        result.append("classfiyName:'" + category.getName() + "',");
        String syncId = StringUtils.null2String(calendar.getSyncId());
        result.append("syncId:'" + syncId + "',");
        if(calendar.getDegreeOfImportance() == null) {
            result.append("degreeOfImportance:'1',");
        }else {
            result.append("degreeOfImportance:'"+calendar.getDegreeOfImportance()+"',");
        }
        result.append("classfiyColor:'" + category.getBackColor() + "',");
        if(isComplate){
            result.append("color:'#3f3f3f'").append("}");
        }else {
            result.append("color:'" + category.getBackColor() + "'").append("}");
        }
        return result.toString();
    }





    /**
     * 获取个人日程、系统日程或共享日程，月视图查询日程方法(临时增加，给日程提醒查询用)
     * @param userId
     * @param corpId
     * @param title
     * @param category
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("unused")
    public String getOaCalendarTem(String sharedId, String userId, String corpId, String title, String category, String viewType, String start, String end, String token, String leader) throws ParseException{
        if (StringUtils.isNotEmpty(title)) {
            title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
        }
        LOG.debug("走的临时方法");
        //获取当前用户的参与日程和拥有日程
        List<Calendar> list = new ArrayList<Calendar>();
        Date startDate = null,endDate = null;
        List<String> maintainFieldValue = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){}else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){}else{
                List<String> sysCate = new ArrayList<>();
                if(StringUtils.isNotEmpty(leader)) {
                    sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
                }
                if(sysCate.isEmpty()){
                    sysCate.add("1");
                }
                //领导日程查询和定时提醒任务查询
                if("1".equals(leader) || StringUtils.equals("remind", leader)) {
                    if(StringUtils.equals("1", leader)) {}else {
                        list = this.calendarDao.findRemindOaCalendarNoSysNoRepeat("%"+title+"%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                    }
                }
            }
        }
        StringBuffer json = new StringBuffer();
        json.append("[");
        if(list!=null && !list.isEmpty()){
            String isComplateId = sharedId;
            String complateType = "1";
            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            List<String> calendarCategorys = new ArrayList<String>();
            String calendarCategoryFlag = "";
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                String calendarId = calendar.getId();
                String calendarCategory = calendar.getCalendarCategory();
                calendarIds.add(calendarId);
                if(!StringUtils.equals(calendarCategoryFlag, calendarCategory)) {
                    calendarCategorys.add(calendarCategory);
                    calendarCategoryFlag = calendarCategory;
                }
            }
            List<CalendarDelete> deletes = new ArrayList<>();
            deletes = this.calendarDeleteDao.findByBelongs(calendarIds, CalendarUtils.getDataByStr(end, "yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deletes) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }
            //----end----
            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryByIds(calendarCategorys, corpId);
            Map<String,CalendarCategory> categorysMap = new HashMap<String,CalendarCategory>();
            for (CalendarCategory calendarCategory : categorys) {
                categorysMap.put(calendarCategory.getId(), calendarCategory);
            }
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeats = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeats) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }

            /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
            List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
            Map<String,List<String>> partFinishedMap = new HashMap<>();
            for(String calendarId : calendarIds){
                List<String> partIdList = new ArrayList<>();
                for(CalendarFinished calendarFinished : calendarFinishedList){
                    if(calendarId.equals(calendarFinished.getCalendarId())){
                        partIdList.add(calendarFinished.getPartId());
                    }
                }
                partFinishedMap.put(calendarId,partIdList);
            }

            //---end----
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                if(calendar != null){
                    String jsonString = this.getCalendarInfo(complateType,isComplateId,calendar,start,end,viewType,userId,corpId,maintainFieldValue,deletesMap,categorysMap,repeatsMap,partFinishedMap);
                    if(StringUtils.isNotBlank(jsonString)) {
                        json.append(jsonString);
                        if(i != list.size()-1){
                            json.append(",");
                        }
                    }
                }
            }
        }
        return json.append("]").toString();
    }

    /**
     * 获取日程设置表中初始化的值
     * @param corpId
     * @return
     */
    public List<String> getSysSources(String corpId){
        CalendarSetting oca = this.calendarSettingDao.getCalendarSettingValue("oaSysCalendarSet", corpId);
        List<String> source = new ArrayList<>();
        //系统日程设置打开
        if("0".equals(oca.getSettingValue())){
            source.add("");
        }else{
            CalendarSetting set = this.calendarSettingDao.getCalendarSettingValue("calendarSource", corpId);
            String setting = StringUtils.null2String(set.getSettingValue());
            //日程来源的值
            if(!"".equals(setting)){
                String[] sources = setting.split(",");
                for (String str : sources) {
                    source.add(str);
                }
            }else{
                source.add("");
            }
        }
        return source;
    }

    /**
     * 概览模式导出时，查询某一周的日程
     * @param userId
     * @param corpId
     * @param viewType
     * @param start
     * @param end
     * @param token
     * @param exportType myCalendar:从我的日程进来,leaderCalendar:从领导日程进来
     * @return
     */
    public List<Map<String, String>> getOaWeekCalendarList(String userId,String corpId,String viewType,String start,String end,String token,String exportType){
        WebUser user = WebUtils.getCurrentUser();
        List<Map<String, String>> result = null;
        if(StringUtils.equals(user.getUserId(), userId) && StringUtils.equals("myCalendar", exportType)) {
            //我的日程
            result = getOaCalendarList(null,"","",userId,corpId,"",viewType,start,end,token,userId,"calendar","","");
        }else {
            //不是我的日程
            result = getOaCalendarList(null,"","",userId,corpId,"",viewType,start,end,token,userId,"leaderOrSubCalendar","","");
            //对数据结果进行处理，把我的
        }
        //根据map中的startWeek字段进行排序
        if(CollectionUtils.isNotEmpty(result)) {
            Collections.sort(result, new Comparator<Map<String,String>>(){
                @Override
                public int compare(Map<String,String> o1, Map<String,String> o2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date date1 = null;
                    Date date2 = null;
                    try {
                        date1 = format.parse(StringUtils.equals(o1.get("isAllDay"), "1")?o1.get("startWeek")+" 00:00":o1.get("startWeek"));
                        date2 = format.parse(StringUtils.equals(o2.get("isAllDay"), "1")?o2.get("startWeek")+" 00:00":o2.get("startWeek"));
                    }catch (ParseException e) {
                        LOG.error("时间转换异常",e);
                    }
                    return date1.compareTo(date2);
                }
            });
        }
        return result;
    }

    /**
     * 获取个人日程、系统日程或共享日程，列表视图查询方法
     * @param pageable 分页参数 Pageable
     * @param sharedId 共享人、领导id
     * @param category 日程分类
     * @param userId 用户id
     * @param corpId 单位Id
     * @param title 日程标题
     * @param viewType 查看类型 点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
     * @param start 查询开始时间
     * @param end 查询结束时间
     * @param token 令牌信息
     * @param nowUserId 当前用户Id
     * @param moduleType 查询类型 portletLeaderCalendar 来自日程部件-领导日程  leaderWeekCalendar-日程部件-一周领导日程 leaderOrSubCalendar 领导日程、下属日程  report 来自汇报模块 calendar 我的日程
     * @param ingOrFinish ing 查询进行中 finish 查询已完成 allCancel 不查询
     * @param leaderCustWeekType
     * @return List<Map<String, String>>
     */
    public List<Map<String, String>> getOaCalendarList(Pageable pageable, String sharedId, String category,
                                                       String userId, String corpId, String title, String viewType, String start, String end,
                                                       String token, String nowUserId , String moduleType, String ingOrFinish,
                                                       String leaderCustWeekType){
        //获取当前用户的参与日程和拥有日程
        List<String> maintainFieldValue = new ArrayList<>();
        Date startDate = null,endDate = null;
        List<Map<String, String>> maps = new ArrayList<>();
        List<Map> calList ;
        Map<String,Object> mapValue = new HashMap<String,Object>();
        List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();

        //字符串转时间
        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        //设置起止时间  00：00：00-23：59：59
        GregorianCalendar gc1 = new GregorianCalendar();
        gc1.setTime(startDate);
        gc1.set(java.util.Calendar.HOUR_OF_DAY,0);
        gc1.set(java.util.Calendar.MINUTE,0);
        gc1.set(java.util.Calendar.SECOND,0);
        startDate = gc1.getTime();
        gc1.setTime(endDate);
        gc1.set(java.util.Calendar.HOUR_OF_DAY,23);
        gc1.set(java.util.Calendar.MINUTE,59);
        gc1.set(java.util.Calendar.SECOND,59);
        endDate = gc1.getTime();


        //获取排序规则
        Sort sort = pageable == null ? null : pageable.getSort();
        String orderBy = "";
        if(sort != null){
            orderBy = " order by ";
            for (Order order : sort) {
                orderBy += order.getProperty() + " " + order.getDirection().name();
            }
        }
        if("".equals(orderBy) || " order by ".equals(orderBy)){
            orderBy = "order by start_date desc";
        }
        if(StringUtils.equals("portletLeaderCalendar", moduleType)) {//日程部件里领导日程按时间升序排序
            orderBy = "order by start_date";
        }
        if(StringUtils.equals("0", leaderCustWeekType)) {
            orderBy = "order by dutyLevel,initialism,calendar_owner,amOrPm desc,start_date,start_time";
        }

        //sql语句，查询时间范围内的日程
        StringBuffer sql = new StringBuffer();
        sql.append(" select o.id,o.createdBy,o.is_complate,o.title,o.start_date,o.end_date,o.start_time,o.content,o.address,o.end_time,o.calendar_owner,o.duplicate_type,o.duplicate_interval,o.week_month_duplicateType as week_month,");
        sql.append(" o.duplicate_end_type,o.duplicate_end_type_value,o.is_main,c.name as category,o.participant as participant2, o.set_time_flag as setTimeFlag,su.user_name as username,");
        sql.append(" o.maintainer caleMaintain,c.maintainer cateMaintain,o.belong_calendar,o.calendar_category,o.sync_id,o.degree_of_importance,o.is_all_day,c.back_color,so.org_name_path,case when sd.duty_level is not null then sd.duty_level else 999999 end as dutyLevel,su.initialism,CASE WHEN o.start_time > 43200 THEN '0' ELSE '1' END AS amOrPm from oa_calendar o ");
        sql.append(" left join oa_calendar_category c on c.id=o.calendar_category left join sys_user su on o.calendar_owner = su.id left join sys_org so on su.org_id=so.id left join sys_duty sd on su.duty_id=sd.id ");
        if(StringUtils.equals(moduleType, "report")) {//汇报调用
            sql.append("where (( o.start_date <= :startDate and o.end_date >= :startDate) or ( o.start_Date >= :startDate and o.end_date <= :endDate) or (o.start_Date <= :endDate and o.end_date >= :endDate) or ( o.start_date >= :startDate and o.start_date <= :endDate and o.is_all_day = 1 ) ) or o.duplicate_type != 'no') and o.corp_id=:corpId ");
        }else {
            sql.append("where (( (o.end_date >= :startDate and o.start_date <= :startDate) or (o.start_date >= :startDate and o.start_date <= :endDate ) ) or o.duplicate_type != 'no') and o.corp_id=:corpId  ");
        }

        mapValue.put("startDate", startDate);
        mapValue.put("endDate", endDate);
        mapValue.put("corpId", corpId);

        if(StringUtils.isNotBlank(title)){
            sql.append(" and o.title like  "+ "'%"+title+"%' ");
        }
        if("share".equals(viewType)){//领导日程、下属日程、共享日程
            List<String> shareCalFieldValue = new ArrayList<>();
            List<String> shareCatFieldValue = new ArrayList<>();
            List<String> cates = new ArrayList<>();
            List<String> source = this.getSysSources(corpId);
            sql.append("and o.sync_module is null ");
            if(StringUtils.isEmpty(sharedId)) {//共享日程选择'全部'
                List<String> shareIdList = new ArrayList<>();
                //查出所有共享人
                List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                for(Map<String, String> map : shareUserList) {
                    shareIdList.add(map.get("userId"));
                }
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    //共享日程
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);
                    //共享分类
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);

                    cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
                }
                //所属人日程
                shareIdList.add("");
                if(CollectionUtils.isNotEmpty(shareIdList)){
                    sql.append(" and o.calendar_owner in (:shareIdList) ");
                    mapValue.put("shareIdList", shareIdList);
                }

                //日程设置可分享、可维护
                shareCalFieldValue.add("");
                if(CollectionUtils.isNotEmpty(shareCalFieldValue)){
                    sql.append(" and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) ");
                    mapValue.put("shareCalFieldValue", shareCalFieldValue);
                }else{
                    sql.append(" and ( 1=1 ");
                }

                //日程分类可查看、可维护
                cates.add("");
                if(CollectionUtils.isNotEmpty(cates)){
                    sql.append(" or o.calendar_category in (:cates) ");
                    mapValue.put("cates", cates);
                }

                sql.append(" ) ").append(orderBy);
                maintainFieldValue = this.getAllMaintainFieldValue(userId,shareIdList,corpId,token);
            }else {//共享日程选择具体人
                //共享日程
                shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);
                //共享分类
                shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
                if(cates.isEmpty()){
                    cates.add("");
                }
                if(!"".equals(category)){
                    List<String> categories = Arrays.asList(category.split(","));
                    sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) and o.calendar_category not in (:categories) ");
                    sql.append(orderBy);
                    mapValue.put("sharedId", sharedId);
                    mapValue.put("shareCalFieldValue", shareCalFieldValue);
                    mapValue.put("cates", cates);
                    mapValue.put("categories", categories);
                }else{
                    sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) ").append(orderBy);
                    mapValue.put("sharedId", sharedId);
                    mapValue.put("shareCalFieldValue", shareCalFieldValue);
                    mapValue.put("cates", cates);
                    maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
                }
            }
        }else{
            List<String> userIdList = Arrays.asList(userId.split(","));
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                //获取参与日程分类
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    List<String> categories = Arrays.asList(category.split(","));
                    if(categories.contains(cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    //我的日程列表页，取消某一日程分类查询
                    if(StringUtils.equals("calendar", moduleType)) {
                        sql.append("and o.calendar_owner=:userId and o.calendar_category not in (:categories) ");
                    }else {//领导日程，下属日程列表页，选择某一日程分类查询
                        sql.append("and ((o.calendar_owner=:userId and o.calendar_category not in (:categories)) or o.participant in (:partFieldValue)) and (c.code not in ('singlePerson','calendarSysPerson') or c.code is null) ").append(orderBy);
                    }
                    String leaderSql = sql.toString();
                    leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程' AS category").replace("and o.calendar_owner=:userId", "");
                    sql.append(" union all ");
                    sql.append(" " +leaderSql+" ");
                    sql.append(" and (o.participant in (:partFieldValue)) ").append(orderBy);
                    mapValue.put("userId", userId);
                    mapValue.put("categories", categories);
                    mapValue.put("partFieldValue", partFieldValue);
                }else{
                    if("partCalendar".equals(cate.getCode())){
                        sql.append("and o.participant in (:partFieldValue) ").append(orderBy);
                        mapValue.put("partFieldValue", partFieldValue);
                    }else{
                        sql.append("and o.calendar_category=:category ").append(orderBy);
                        mapValue.put("category", category);
                    }
                }
            }else{
                //一周领导日程、领导日程列表、下属日程列表不显示领导或下属私人日程
                StringBuffer sb = new StringBuffer(sql);
                if(StringUtils.equals(moduleType, "leaderWeekCalendar") || StringUtils.equals(moduleType, "leaderOrSubCalendar") || StringUtils.equals(moduleType,"portletLeaderCalendar")) {
                    sql.append("and (c.code not in ('calendarSysPerson','singlePerson') or c.code is null) ");
                }
                //sb.append(" and (o.sync_module is null or o.sync_module = '') ");
                sql.append("and c.category != 'calendarSys' ");
                String leaderSql = sb.toString();
                leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程'AS category");
                sql.append("and (o.calendar_owner in (:userId)) ");
                sql.append(" union all ");
                sql.append(" " +leaderSql+" ");
                sql.append(" and (o.participant in (:partFieldValue)) ").append(orderBy);
                mapValue.put("userId", userIdList);
                mapValue.put("partFieldValue", partFieldValue);
            }
        }
        calList = super.findByListNativeQuery(sql.toString(), "",mapValue);
        //获取参与日程分类
        List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
        CalendarCategory cate = null;
        if (CollectionUtils.isNotEmpty(cates)) {
            cate = cates.get(0);
        }
        if(calList!=null && !calList.isEmpty()){
            Map<String,String> textParams = new HashMap<String,String>();
            textParams.put("corpId", corpId);
            for(int i=0;i<calList.size();i++){
                Map obj =  calList.get(i);
                String calendarStart = CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy-MM-dd");
                String calendarEnd = (Date) obj.get("end_date")==null ? calendarStart : CalendarUtils.getStrByDate((Date) obj.get("end_date"), "yyyy-MM-dd");
                String calendarId = obj.get("id").toString();
                int sflag1 = CalendarUtils.compareDateStr(calendarStart, start);
                int eflag1 = CalendarUtils.compareDateStr(calendarStart, end);
                int sflag2 = CalendarUtils.compareDateStr(calendarEnd, start);
                int eflag2 = CalendarUtils.compareDateStr(calendarEnd, end);
                String startTime="";
                String endTime="";
                if(!"1".equals(obj.get("is_all_day").toString())){//全天日程
                    startTime = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                    endTime = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                }
                if((sflag1!=1 && sflag2!=2) || (sflag1!=2 && eflag1!=1)){
                    Map<String, String> map = new HashMap<>();
                    //查询当前用户是否已经完成该日程
                    String isComplate = StringUtils.equals("1", StringUtils.null2String(obj.get("is_complate")))?"1":"0";
                    // 20210831 日程标记功能：日程表中isComplate字段不是1，说明只有部分参与人完成日程或者没有参与者完成日程，参与者包括日程创建者自身
                   // if ("0".equals(isComplate)){
                        // 查询日程完成人员ID
                        List<String> partIdList = calendarFinishedDao.findPartId(calendarId);//循环获取，可以优化
                        if(!"leaderOrSubCalendar".equals(moduleType)&&!"share".equals(viewType)&&!"portletLeaderCalendar".equals(moduleType)){//我的日程下，传入的用户可能是参与人
                            // 当前用户是否在日程完成人员ID集合中
                            if (partIdList.contains(userId)) {
                                // 当前用户是完成日程状态
                                isComplate = "1";
                            }else{
                                isComplate = "0";
                            }
                        }else{
                            //songwy add 判断当前所属用户是否存在集合中
                            if (partIdList.contains(obj.get("calendar_owner").toString())) {
                                // 当前用户是完成日程状态
                                isComplate = "1";
                            }else{
                                isComplate = "0";
                            }
                            //songwy add end
                        }

                    if(StringUtils.equals("ing", ingOrFinish)) {
                        if(StringUtils.equals("1", isComplate)) {
                            continue;
                        }
                    }else if(StringUtils.equals("finish", ingOrFinish)) {
                        if(StringUtils.equals("0", isComplate)) {
                            continue;
                        }
                    }else if(StringUtils.equals("allCancel", ingOrFinish)) {
                        break;
                    }
                    map.put("isComplate",isComplate);
                    map.put("isRealCreator", StringUtils.equals(StringUtils.null2String(obj.get("createdBy")), nowUserId)?"true":"false");
                    //共享日程下，还要判断是否有权限处理
//                    if("share".equals(viewType)){
//                        Calendar calendar = new Calendar();
//                        calendar.setCalendarCategory(StringUtils.null2String(obj.get("calendar_category")));
//                        calendar.setMaintainer(StringUtils.null2String(obj.get("cateMaintain")));
//                        String canEdit = this.judgeShareCanEdit(userId,calendar);
//                        map.put("canEdit", canEdit);
//                    }
                    map.put("startDate", CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy年MM月dd日"));
                    map.put("start", calendarStart);
                    map.put("end", calendarEnd);
                    map.put("id", calendarId);
                    map.put("title", obj.get("title").toString());
                    map.put("calendarOwner",obj.get("calendar_owner").toString());
                    map.put("duplicateType",StringUtils.null2String(obj.get("duplicate_type")));
                    map.put("duplicateInterval",StringUtils.null2String(obj.get("duplicate_interval")));
                    map.put("participant2",StringUtils.null2String(obj.get("participant2")));
                    map.put("content",StringUtils.null2String(obj.get("content")));
                    map.put("address",StringUtils.null2String(obj.get("address")));
                    // 是否是上午/下午
                    map.put("setTimeFlag", StringUtils.null2String(obj.get("settimeflag")));

                    // 创建人
                    map.put("createdBy",StringUtils.null2String(obj.get("createdby")));
                    //新加字段，防止旧数据影响
                    if(obj.get("degree_of_importance") == null) {
                        map.put("degreeOfImportance", "1");
                    }else {
                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                    }
                    if(StringUtils.equals(StringUtils.null2String(obj.get("is_all_day")), "0")) {
                        map.put("startTime", startTime);
                        map.put("endTime", endTime);
                        map.put("startWeek", calendarStart+" "+startTime);
                        map.put("endWeek", calendarEnd+" "+endTime);
                        // 上午/下午模式下日程
                        if (StringUtils.equals(StringUtils.null2String(obj.get("settimeflag")), "0")) {
                            map.put("isAmOrPm", "0");
                        } else if (StringUtils.equals(StringUtils.null2String(obj.get("settimeflag")), "1")){
                            map.put("isAmOrPm", "1");
                        }else {
                            map.put("isAmOrPm", Integer.parseInt(startTime.split(":")[0]) >= 12? "0" : "1");
                        }
                    }else {
                        map.put("startWeek", calendarStart+" 00:00");
                        map.put("endWeek", calendarEnd+" 00:00");
                        map.put("isAmOrPm", "2");
                        map.put("startTime","09:00");
                        map.put("endTime", "18:00");
                    }
                    map.put("weekNumber", CalendarUtils.dayOfWeek(calendarStart, "yyyy-MM-dd"));
                    map.put("isAllDay", StringUtils.null2String(obj.get("is_all_day")));
                    if(obj.get("sync_id")==null) {
                        map.put("syncId", StringUtils.null2String(obj.get("syncId")));
                    }else {
                        map.put("syncId", StringUtils.null2String(obj.get("syncId").toString()));
                    }
                    map.put("category", obj.get("category").toString());
                    map.put("repeat","0");
                    map.put("isMain",StringUtils.null2String(obj.get("is_main")));
                    if(StringUtils.equals("参与日程", obj.get("category").toString())){
                        map.put("categoryId", cate.getId());
                        map.put("isMaintain", "0");
                        map.put("color", cate.getBackColor());
                        map.put("duplicate_type",StringUtils.null2String(obj.get("duplicate_type")));
                        if(StringUtils.isNotEmpty(StringUtils.null2String(obj.get("duplicate_type"))) && !StringUtils.equals(StringUtils.null2String(obj.get("duplicate_type")),"no")) {
                            if(StringUtils.equals("1",StringUtils.null2String(obj.get("is_main")))) {
                                map.put("repeat","0");
                            }else {
                                map.put("repeat","1");
                            }
                        }
                    }else {
                        map.put("isMaintain", "1");
                        map.put("categoryId", obj.get("calendar_category").toString());
                        map.put("color", obj.get("back_color").toString());
                    }
                    if("share".equals(viewType)){
                        if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(obj.get("caleMaintain")==null?"":obj.get("caleMaintain").toString())||maintainFieldValue.contains(obj.get("cateMaintain")==null?"":obj.get("cateMaintain").toString()))){
                            map.put("isMaintain", "1");
                            if("0".equals(obj.get("is_main").toString())){
                                Calendar main = this.calendarDao.findById(obj.get("belong_calendar").toString()).get();
                                CalendarCategory mainCate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                                if(maintainFieldValue.contains(StringUtils.null2String(main.getMaintainer()))
                                        ||maintainFieldValue.contains(StringUtils.null2String(mainCate.getMaintainer()))){
                                    map.put("showEditMsg", "1");
                                }
                            }
                        }else{
                            map.put("isMaintain", "0");
                        }
                    }
                    if("1".equals(obj.get("calendar_owner").toString())){
                        map.put("owner", "系统管理员");
                    }else{
                        textParams.put("id",  obj.get("calendar_owner").toString());
                        textParams.put("thirdType", "");

                        //去除循环查询用户
//                        Map<String,Object> scopeName = this.userApiService.getUser( obj.get("calendar_owner").toString(), corpId, "", token);//循环查询
//                        if(MapUtils.isNotEmpty(scopeName)){
//                            map.put("owner", scopeName.get("userName").toString());
//                            map.put("orgNamePath", obj.get("org_name_path").toString());
//                        }
                        map.put("orgNamePath", StringUtils.null2String(obj.get("org_name_path")));
                        map.put("owner", StringUtils.null2String(obj.get("username")));
                    }
                    map.put("belong", obj.get("belong_calendar")==null?calendarId:obj.get("belong_calendar").toString());
                    if("0".equals(obj.get("is_main").toString())){
                        map.put("repeat", "1");
                    }else if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString()) && !"参与日程".equals(map.get("category"))){
                        map.put("repeat", "0");
                    }else if("no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString())) {
                        map.put("repeat", "2");
                    }

                    maps.add(map);
                }
                if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString())){
                    List<Map<String, String>> repeatList ;
                    //根据当前重复日程的重复规则获取指定起止时间的所有 起止时间数组
                    String duplicateInterval = obj.get("duplicate_interval")==null?"":obj.get("duplicate_interval").toString();
                    String duplicateEndTypeValue= obj.get("duplicate_end_type_value")==null?"":obj.get("duplicate_end_type_value").toString();
                    String weekMonthDuplicateType= StringUtils.null2String(obj.get("week_month"));
                    repeatList = this.getDataMsg(obj.get("duplicate_type").toString(),duplicateInterval,obj.get("duplicate_end_type").toString(),duplicateEndTypeValue , calendarStart, calendarEnd, end,weekMonthDuplicateType);
                    if(repeatList!=null && !repeatList.isEmpty()){
                        List<CalendarDelete> deletes ;
                        deletes = this.calendarDeleteDao.findByBelong(calendarId.toString(), endDate);
                        String delFlag = "",calStart = "",calEnd = "";
                        for(int j=0;j<repeatList.size();j++){
                            Map<String, String> date = repeatList.get(j);
                            calStart = date.get("startDate");
                            calEnd = date.get("endDate");
                            int flag = 0;
                            //处理开始时间与结束时间内 如果有被删掉的重复日程
                            if(deletes!=null && !deletes.isEmpty()){
                                for(int k=0;k<deletes.size();k++){
                                    CalendarDelete delete = deletes.get(k);
                                    if(delete != null){
                                        delFlag = delete.getDeleteType();
                                        if("current".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));

                                        }else if("after".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }
                                        if(flag == 0){
                                            break;
                                        }
                                    }
                                }
                                if(flag==0 && "current".equals(delFlag)){
                                    continue;
                                }else if(flag==0 && "after".equals(delFlag)){
                                    break;
                                }
                            }
                            int flag1s = CalendarUtils.compareDateStr(calStart, start);
                            int flag1e = CalendarUtils.compareDateStr(calStart, end);
                            int flag2s = CalendarUtils.compareDateStr(calEnd, start);
                            int flag2e = CalendarUtils.compareDateStr(calEnd, end);
                            if((flag1s!=1 && flag2s!=2) || (flag1s!=2 && flag1e!=1)){
                                List<Calendar> repeats ;
                                repeats = this.calendarDao.findCalendarByBelong(calendarId, startDate, endDate);
                                boolean equal = true;
                                if(repeats!=null && !repeats.isEmpty()){
                                    for(int k=0;k<repeats.size();k++){
                                        Calendar repeat = repeats.get(k);
                                        int flag3 = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                        if(flag3 == 0){
                                            equal = false;
                                            break;
                                        }
                                    }
                                }
                                if(equal){
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", calendarId);
                                    //查询当前用户是否已经完成该日程
                                    String isComplate = StringUtils.equals("1", StringUtils.null2String(obj.get("is_complate")))?"1":"0";
                                    String calendarDate = obj.get("start_date").toString();
                                    if(StringUtils.isNotEmpty(calendarDate)) {
                                        String day = date.get("startDate").toString();
                                        if(!StringUtils.equals(calendarDate, day)) {
                                            isComplate = "0";
                                        }
                                    }
                                    if(StringUtils.equals("ing", ingOrFinish)) {
                                        if(StringUtils.equals("1", isComplate)) {
                                            continue;
                                        }
                                    }else if(StringUtils.equals("finish", ingOrFinish)) {
                                        if(StringUtils.equals("0", isComplate)) {
                                            continue;
                                        }
                                    }else if(StringUtils.equals("allCancel", ingOrFinish)) {
                                        break;
                                    }
                                    map.put("isComplate",isComplate);
                                    map.put("isRealCreator", StringUtils.equals(StringUtils.null2String(obj.get("createdBy")), nowUserId)?"true":"false");
                                    Date d = new Date();

                                    d = CalendarUtils.getDataByStr(date.get("startDate"), "yyyy-MM-dd");

                                    if(obj.get("degree_of_importance") == null) {
                                        map.put("degreeOfImportance", "1");
                                    }else {
                                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                                    }
                                    if(StringUtils.equals(StringUtils.null2String(obj.get("is_all_day")), "0")) {
                                        map.put("startWeek", calStart+" "+startTime);
                                        map.put("endWeek", date.get("endDate")+" "+endTime);
                                        map.put("startTime", startTime);
                                        map.put("endTime", endTime);
                                        map.put("isAmOrPm", Integer.parseInt(startTime.split(":")[0]) >= 12? "0" : "1");
                                    }else {
                                        map.put("startWeek", calStart+" 00:00");
                                        map.put("endWeek", date.get("endDate")+" 00:00");
                                        map.put("isAmOrPm", "2");
                                        map.put("startTime","09:00");
                                        map.put("endTime", "18:00");
                                    }
                                    map.put("calendarOwner",obj.get("calendar_owner").toString());
                                    map.put("isAllDay", StringUtils.null2String(obj.get("is_all_day")));
                                    map.put("startDate", CalendarUtils.getStrByDate(d, "yyyy年MM月dd日"));
                                    map.put("start", calStart);
                                    map.put("end", date.get("endDate"));
                                    map.put("belong", calendarId);
                                    map.put("title", obj.get("title").toString());
                                    map.put("duplicateType",StringUtils.null2String(obj.get("duplicate_type")));
                                    map.put("duplicateInterval",StringUtils.null2String(obj.get("duplicate_interval")));
                                    map.put("participant2",StringUtils.null2String(obj.get("participant2")));
                                    map.put("content",StringUtils.null2String(obj.get("content")));
                                    map.put("address",StringUtils.null2String(obj.get("address")));
                                    map.put("syncId", StringUtils.null2String(obj.get("sync_id")==null?"":obj.get("sync_id").toString()));
                                    map.put("weekNumber", CalendarUtils.dayOfWeek(calStart, "yyyy-MM-dd"));
                                    map.put("isMain","0");
                                    if("1".equals(obj.get("calendar_owner").toString())){
                                        map.put("owner", "系统管理员");
                                    }else{
                                        textParams.put("id", obj.get("calendar_owner").toString());
                                        textParams.put("thirdType", "");
//                                        Map<String,Object> scopeName = this.userApiService.getUser(obj.get("calendar_owner").toString(), corpId, "", token);//循环查询
//                                        if(scopeName!= null && !scopeName.isEmpty()){
//                                            map.put("owner", scopeName.get("userName").toString());
//                                            map.put("orgNamePath", obj.get("org_name_path").toString());
//                                        }
                                        map.put("owner", StringUtils.null2String(obj.get("username")));
                                    }
                                    map.put("category", obj.get("category").toString());
                                    map.put("repeat","1");
                                    if(StringUtils.equals("参与日程", obj.get("category").toString())){
                                        map.put("categoryId", cate.getId());
                                        map.put("isMaintain", "0");
                                        map.put("color", cate.getBackColor());
                                    }else {
                                        map.put("isMaintain", "1");
                                        map.put("categoryId", obj.get("calendar_category").toString());
                                        map.put("color", obj.get("back_color").toString());
                                    }
                                    if("share".equals(viewType)){
                                        if(maintainFieldValue.contains(obj.get("caleMaintain")==null?"":obj.get("caleMaintain").toString())||maintainFieldValue.contains(obj.get("cateMaintain")==null?"":obj.get("cateMaintain").toString())){
                                            map.put("isMaintain", "1");
                                            map.put("showEditMsg", "1");
                                        }else{
                                            map.put("isMaintain", "0");
                                        }
                                    }

                                    //对数据进行处理

                                    maps.add(map);
                                }
                            }
                            if(flag1e == 1){
                                break;
                            }
                        }
                    }
                }
            }
        }
        if(mapList!=null&&!mapList.isEmpty()) {
            maps.addAll(mapList);
        }
        return maps;
    }

    /*
     * PC端将任务json转换成可在日程列表中展示的数据
     */
    private List<Map<String, String>> taskList(String sysList, CalendarCategory cat, String type) {
        Map<String,Object> scopeName = JsonUtils.readValue(sysList);
        List<Map<String, String>> maplist = new ArrayList<Map<String, String>>();
        List<Map<String,Object>> map = (List<Map<String, Object>>) scopeName.get("data");
        Map<String,Object> data;
        if(map != null && !map.isEmpty()) {
            for(int i =0;i<map.size();i++) {
                Map<String, String> mapString = new HashMap<String,String>();
                data = map.get(i);
                if("task".equals(type)) {
                    mapString.put("start", data.get("end_date").toString().substring(0,10));
                    mapString.put("end",  data.get("end_date").toString().substring(0,10));
                    mapString.put("id", data.get("id").toString());
                    mapString.put("startWeek", data.get("end_date").toString());
                    mapString.put("endWeek",  data.get("end_date").toString());
                    if(data.get("parent_id")!=null&&!"".equals(data.get("parent_id").toString())) {
                        mapString.put("title", "(子任务)"+data.get("title").toString());
                    }else {
                        mapString.put("title", "(父任务)"+data.get("title").toString());
                    }
                    mapString.put("category", "任务");
                    mapString.put("isMaintain", "-1");
                    mapString.put("startDate",data.get("end_date").toString().substring(0, 4)+"年"+data.get("end_date").toString().substring(5, 7)+"月"+data.get("end_date").toString().substring(8, 10)+"日");
                }else if("meeting".equals(type)) {
                    mapString.put("start", data.get("startTime").toString().substring(0,10));
                    mapString.put("end",  data.get("endTime").toString().substring(0,10));
                    mapString.put("startWeek", data.get("startTime").toString());
                    mapString.put("endWeek",  data.get("endTime").toString());
                    mapString.put("id", data.get("id").toString());
                    mapString.put("title", data.get("name").toString());
                    mapString.put("category", "会议");
                    mapString.put("startDate",data.get("startTime").toString().substring(0, 4)+"年"+data.get("startTime").toString().substring(5, 7)+"月"+data.get("startTime").toString().substring(8, 10)+"日");
                    mapString.put("endDate",data.get("endTime").toString().substring(0, 4)+"年"+data.get("endTime").toString().substring(5, 7)+"月"+data.get("endTime").toString().substring(8, 10)+"日");
                    mapString.put("isMaintain", "-2");
                }
                mapString.put("color" , cat.getBackColor());
                mapString.put("isAllDay","0");
                mapString.put("owner", WebUtils.getCurrentUser().getCnName());
                mapString.put("belong", "");
                mapString.put("categoryId", cat.getId());
                mapString.put("backColor", cat.getBackColor());
                mapString.put("syncId", "");
                maplist.add(mapString);
            }
            return maplist;
        }
        return null;
    }

    /*
     * 移动端将任务json转换成可在日程列表中展示的数据
     */
    private List<Map<String, String>> taskListPhone(String sysList, CalendarCategory cat, String type) {
        Map<String,Object> scopeName = JsonUtils.readValue(sysList);
        List<Map<String, String>> maplist = new ArrayList<Map<String, String>>();
        List<Map<String,Object>> map = (List<Map<String, Object>>) scopeName.get("data");
        Map<String,Object> data ;
        if(map!=null && !map.isEmpty()) {
            for(int i =0;i<map.size();i++) {
                Map<String, String> mapString = new HashMap<String,String>();
                data = map.get(i);
                if("task".equals(type)) {
                    if(data.get("parent_id")!=null&&!"".equals(data.get("parent_id").toString())) {
                        mapString.put("title", "(子任务)"+data.get("title").toString());
                    }else {
                        mapString.put("title", "(父任务)"+data.get("title").toString());
                    }
                    mapString.put("startDate",data.get("end_date").toString().substring(0, 4)+"年"+data.get("end_date").toString().substring(5, 7)+"月"+data.get("end_date").toString().substring(8, 10)+"日");
                    mapString.put("start", data.get("end_date").toString().substring(0,10));
                    mapString.put("end",  data.get("end_date").toString().substring(0,10));
                    mapString.put("isAllDay", "1");
                    mapString.put("isMaintain", "-1");
                    mapString.put("category", "任务");
                }else if("meeting".equals(type)) {
                    mapString.put("title",data.get("name").toString());
                    mapString.put("startDate",data.get("startTime").toString().substring(0, 4)+"年"+data.get("startTime").toString().substring(5, 7)+"月"+data.get("startTime").toString().substring(8, 10)+"日");
                    mapString.put("start", ((String) data.get("startTime")));
                    mapString.put("end",  ((String) data.get("endTime")));
                    mapString.put("isAllDay", "0");
                    mapString.put("isMaintain", "-2");
                    mapString.put("category", "会议");
                }
                mapString.put("owner", WebUtils.getCurrentUser().getCnName());
                mapString.put("belong", "");
                mapString.put("id", data.get("id").toString());
                mapString.put("backColor", cat.getBackColor());
                mapString.put("categoryId", cat.getId());
                mapString.put("syncId", "");
                if(data.get("content")!=null) {
                    mapString.put("content", data.get("content").toString());
                }else {
                    mapString.put("content", "");
                }
                maplist.add(mapString);
            }
            return maplist;
        }
        return null;
    }

    /**
     * 获取个人日程
     * @param userId
     * @param corpId
     * @param start
     * @param end
     * @param token
     * @param showNumber
     * @param userType
     * @return
     */
    public List<Map<String, String>> getAllOaCalendar(String userId, String sharedId, String viewType, String corpId,String start,String end,String token, int showNumber, String userType,String leaderOrSub){
        //获取当前用户的参与日程和拥有日程
        Date startDate = null,endDate = null;
        List<Map<String, String>> maps = new ArrayList<>();
        List<Map> calList ;
        Map<String,Object> mapValue = new HashMap<String,Object>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        //门户日程部件工作周模式列表视图end值不为空，其他调用此方法的end都为空
        if(StringUtils.isNotBlank(end)) {
            endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");
        }else {
            endDate = startDate;
        }

        StringBuffer sql = new StringBuffer();
        sql.append("select o.id,o.is_complate,o.title,o.createdBy,o.maintainer calendarMaintain,o.week_month_duplicateType week_month,o.start_date,o.end_date,o.calendar_owner,o.duplicate_type,o.duplicate_interval,");
        sql.append("su.user_name userName,o.duplicate_end_type,o.duplicate_end_type_value,o.is_main,c.back_color,o.participant as participant,");
        if("share".equals(viewType)) {
            sql.append("c.name category,");
        }else {
            sql.append(" case when o.calendar_owner not in (:userId) then '参与日程' else c. NAME end as category,");
        }

//        sql.append(" case when o.createdBy not in (:userId) then '参与日程' else c. NAME end as category,");

        sql.append("c.maintainer cateMaintain,o.belong_calendar,o.calendar_category,o.start_time,o.end_time,o.is_all_day,o.content,o.degree_of_importance,o.address from oa_calendar o ");
        sql.append("left join oa_calendar_category c on c.id=o.calendar_category left join sys_user su on o.calendar_owner=su.id ");
        if(StringUtils.isNotBlank(end)) {
            //工作周模式列表视图只查开始时间位于所查时间范围内的日程
            sql.append("where ((o.start_date >= :startDate and (o.start_date<=:endDate or o.end_date is NULL)) or o.duplicate_type != 'no') and o.corp_id=:corpId ");//		Query query = null;
            mapValue.put("endDate", endDate);
        }else {
            sql.append("where ((o.start_date <= :startDate and (o.end_date>=:startDate or o.end_date is NULL)) or o.duplicate_type != 'no') and o.corp_id=:corpId ");//		Query query = null;
        }
        mapValue.put("startDate", startDate);
        mapValue.put("corpId", corpId);
        if("share".equals(viewType)){
            List<String> shareCalFieldValue = new ArrayList<>();
            List<String> shareCatFieldValue = new ArrayList<>();
            List<String> source = this.getSysSources(corpId);
            List<String> cates = new ArrayList<>();
            if(StringUtils.isEmpty(sharedId)) {//共享人为空
                List<String> shareIdList = new ArrayList<>();
                //查出所有共享人
                List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                for(Map<String, String> map : shareUserList) {
                    shareIdList.add(map.get("userId"));
                }
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);//共享日程
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);//共享分类
                }
                if(CollectionUtils.isEmpty(shareIdList)&&CollectionUtils.isEmpty(shareCatFieldValue)&&CollectionUtils.isEmpty(shareCalFieldValue)) {
                    return null;
                }
                cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
            }else {
                //共享日程
                shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);
                //共享分类
                shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
            }
            if(cates.isEmpty()){
                cates.add("");
            }
            sql.append("and o.sync_module is null ");
            if(StringUtils.isNotEmpty(sharedId)) {
                sql.append(" and o.calendar_owner=:sharedId ");
                mapValue.put("sharedId", sharedId);
            }
            sql.append("and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) order by start_time asc ");
            mapValue.put("shareCalFieldValue", shareCalFieldValue);
            mapValue.put("cates", cates);
        }else{
            List<String> userIdList = Arrays.asList(userId.split(","));
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            StringBuffer sb = new StringBuffer(sql);
            sql.append("and c.category != 'calendarSys' ");
            if("1".equals(leaderOrSub)) {
                sql.append(" and ((o.calendar_owner in (:userId) and (c.code not in ('singlePerson','calendarSysPerson') or c.code is null)) ");
            }else {
                sql.append("and (o.calendar_owner in (:userId) ");
            }

//			String leaderSql = sb.toString();
//			leaderSql = leaderSql.replaceAll("c.name category", "'参与日程' category");
            sql.append(" or o.participant in (:partFieldValue) ) order by start_date asc,start_time asc");
//			sql.append("and (o.calendar_owner in (:userId))");
//			sql.append(" union all ");
//			sql.append(" " +leaderSql+" ");
//			sql.append(" and (o.participant in (:partFieldValue)) order by start_date asc,start_time asc ");
            mapValue.put("userId", userIdList);
            mapValue.put("partFieldValue", partFieldValue);
        }
//        LOG.error("sql:"+sql.toString()+"   mapValue:"+JSON.toJSONString(mapValue));
        calList = super.findByListNativeQuery(sql.toString(), "",mapValue);
        if(calList!=null && !calList.isEmpty()){
            Map<String,String> textParams = new HashMap<String,String>();
            textParams.put("corpId", corpId);
            for(int i=0;i<calList.size();i++){
                Map obj =  calList.get(i);
                String calendarStart = CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy-MM-dd");
                String calendarEnd = (Date) obj.get("end_date")==null ? calendarStart : CalendarUtils.getStrByDate((Date) obj.get("end_date"), "yyyy-MM-dd");
                String startTime = "",endTime = "";
                if(!"1".equals(obj.get("is_all_day").toString())){//全天日程
                    startTime = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                    endTime = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                }
                int ssflag = CalendarUtils.compareDateStr(calendarStart, start);
                int esflag = CalendarUtils.compareDateStr(calendarEnd, start);
                int weekEsflag = StringUtils.isNotBlank(end) ? CalendarUtils.compareDateStr(calendarStart, end) : -1;
                String calendarId =obj.get("id").toString();
                if(StringUtils.isNotBlank(end) ? ssflag!=2 && weekEsflag!=1 : ssflag!=1 && esflag!=2){
                    Map<String, String> map = new HashMap<>();
                    //查询当前用户是否已经完成该日程
                    String isComplate = "0";

                    List<String> partIdList = new ArrayList<>();
                    partIdList = calendarFinishedDao.findPartId(calendarId);
                    if("1".equals(leaderOrSub) || "share".equals(viewType)){//领导、下属日程下 如果日程拥有人完成就是日程完成了
                        if (partIdList.contains(obj.get("calendar_owner").toString())) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }else{//我的日程
                        // 当前用户是否在日程完成人员ID集合中
                        if (partIdList.contains(userId)) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }


                    map.put("isComplate",isComplate);
                    map.put("participant2",StringUtils.null2String(obj.get("participant")));
                    map.put("createdBy",StringUtils.null2String(obj.get("createdBy")));
                    map.put("address",StringUtils.null2String(obj.get("address")));
                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                    map.put("isRealCreator",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                    String calendarMaintain = StringUtils.null2String(obj.get("calendarMaintain"));
                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                    //维护权限
                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                        map.put("limitForMaintain","1");
                        map.put("isMaintain","1");
                    }else {
                        map.put("limitForMaintain","0");
                        map.put("isMaintain","0");
                    }
                    if(!"1".equals(obj.get("is_all_day").toString())){//全天日程
                        calendarStart = calendarStart + " " + startTime;
                        calendarEnd = calendarEnd + " " + endTime;
                        map.put("isAllDay", "0");
                    }else{
                        map.put("isAllDay", "1");
                    }
                    if(obj.get("content") == null) {
                        map.put("content", "");
                    }else {
                        map.put("content", obj.get("content").toString());
                    }
                    map.put("weekNumber", CalendarUtils.dayOfWeek2(calendarStart, "yyyy-MM-dd"));
                    map.put("start", calendarStart);
                    map.put("end", calendarEnd);
                    map.put("id", calendarId);
                    map.put("category", obj.get("category")+"");
                    map.put("userName", obj.get("userName")+"");
                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                    }else {
                        map.put("degreeOfImportance", "1");
                    }
                    map.put("title", obj.get("title").toString());
                    if(StringUtils.equals(StringUtils.null2String(obj.get("category")), "参与日程")) {
                        map.put("backColor", "#92d050");
                    }else {
                        map.put("backColor", obj.get("back_color").toString());
                    }
                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                    map.put("belong", obj.get("belong_calendar")==null?calendarId:obj.get("belong_calendar").toString());
                    if("0".equals(obj.get("is_main").toString())){
                        map.put("repeat", "1");
                    }else if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString()) && !"参与日程".equals(obj.get("category").toString())){
                        map.put("repeat", "0");
                    }
                    maps.add(map);
                }
                if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString())){
                    List<Map<String, String>> repeatList ;
                    String duplicateInterval = "";
                    if(obj.get("duplicate_interval")!=null) {
                        duplicateInterval = obj.get("duplicate_interval").toString();
                    }
                    repeatList = this.getDataMsg(obj.get("duplicate_type").toString(),duplicateInterval , obj.get("duplicate_end_type").toString(), obj.get("duplicate_end_type_value")==null?"":obj.get("duplicate_end_type_value").toString(), calendarStart, calendarEnd, start,StringUtils.null2String(obj.get("week_month")));
                    if(repeatList!=null && !repeatList.isEmpty()){
                        List<CalendarDelete> deletes = new ArrayList<>();
                        deletes = this.calendarDeleteDao.findByBelong(calendarId.toString(), endDate);
                        String delFlag = "",calStart = "",calEnd;
                        for(int j=0;j<repeatList.size();j++){
                            Map<String, String> date = repeatList.get(j);
                            calStart = date.get("startDate");
                            calEnd = date.get("endDate");
                            int flag = 0;
                            if(deletes!=null && !deletes.isEmpty()){
                                for(int k=0;k<deletes.size();k++){
                                    CalendarDelete delete = deletes.get(k);
                                    if(delete != null){
                                        delFlag = delete.getDeleteType();
                                        if("current".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));

                                        }else if("after".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }
                                        if(flag == 0){
                                            break;
                                        }
                                    }
                                }
                                if(flag==0 && "current".equals(delFlag)){
                                    continue;
                                }else if(flag==0 && "after".equals(delFlag)){
                                    break;
                                }
                            }
                            int flag1 = CalendarUtils.compareDateStr(calStart, start);
                            int flag2 = CalendarUtils.compareDateStr(calEnd, start);
                            int weekFlag2 = StringUtils.isNotBlank(end) ? CalendarUtils.compareDateStr(calStart, end) : -1;
                            if(StringUtils.isNotBlank(end) ? flag1!=2 && weekFlag2!=1 : flag1!=1 && flag2!=2){
                                List<Calendar> repeats ;
                                repeats = this.calendarDao.findCalendarByBelong(calendarId);
                                boolean equal = true;
                                if(repeats != null && !repeats.isEmpty()){
                                    for(int k=0;k<repeats.size();k++){
                                        Calendar repeat = repeats.get(k);
                                        int flag3 = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                        if(flag3 == 0){
                                            equal = false;
                                            break;
                                        }
                                    }
                                }
                                if(equal){
                                    Map<String, String> map = new HashMap<>();
                                    //查询当前用户是否已经完成该日程
                                    String isComplate = StringUtils.equals("1", StringUtils.null2String(obj.get("is_complate")))?"1":"0";
                                    String calendarDate = obj.get("start_date").toString();
                                    if(StringUtils.isNotEmpty(calendarDate)) {
                                        String day = date.get("startDate").toString();
                                        if(!StringUtils.equals(calendarDate, day)) {
                                            isComplate = "0";
                                        }
                                    }

                                    map.put("isComplate",isComplate);
                                    map.put("participant2",StringUtils.null2String(obj.get("participant")));
                                    map.put("address",StringUtils.null2String(obj.get("address")));
                                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                                    map.put("isRealCreator",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                                    String calendarMaintain = StringUtils.null2String(obj.get("calendarMaintain"));
                                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                                    //维护权限
                                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                                        map.put("limitForMaintain","1");
                                        map.put("isMaintain","1");
                                    }else {
                                        map.put("limitForMaintain","0");
                                        map.put("isMaintain","0");
                                    }
                                    map.put("duplicate_type",obj.get("duplicate_type").toString());
                                    map.put("id", calendarId);
                                    map.put("category", obj.get("category")+"");
                                    map.put("userName", obj.get("userName")+"");
                                    if(!"1".equals(obj.get("is_all_day").toString())){//全天日程
                                        calendarStart = calStart + " " + startTime;
                                        calendarEnd = calEnd + " " + endTime;
                                        map.put("isAllDay", "0");
                                    }else{
                                        map.put("isAllDay", "1");
                                        calendarStart = calendarEnd = calStart;
                                    }
                                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                                    }else {
                                        map.put("degreeOfImportance", "1");
                                    }
                                    map.put("weekNumber", CalendarUtils.dayOfWeek2(calendarStart, "yyyy-MM-dd"));
                                    map.put("start", calendarStart);
                                    map.put("end", calendarEnd);
                                    map.put("belong", calendarId);
                                    map.put("title", obj.get("title").toString());
                                    if(obj.get("content")== null) {
                                        map.put("content", "");
                                    }else {
                                        map.put("content", obj.get("content").toString());
                                    }
                                    if(StringUtils.equals(StringUtils.null2String(obj.get("category")), "参与日程")) {
                                        map.put("backColor", "#92d050");
                                    }else {
                                        map.put("backColor", obj.get("back_color").toString());
                                    }
                                    map.put("repeat", "1");
                                    maps.add(map);
                                }
                            }
                        }
                    }
                }
                if(showNumber>=0 && maps.size() == showNumber){
                    break;
                }
            }
        }
        if(StringUtils.isNotBlank(end)) {
            return maps;
        }else {
            return compareByStartTime(maps);
        }
    }

    /**
     * 获取有日程的日期
     * @param sharedId
     * @param userId
     * @param corpId
     * @param viewType
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    public List<Map<String, String>> getOaCalendarDate(String sharedId, String userId, String corpId, String viewType, String start, String end,String token,String leaderOrSub) throws ParseException{
        //获取当前用户的参与日程和拥有日程
        List<Calendar> list = new ArrayList<>();
        Date startDate = null,endDate = null;
        List<Map<String, String>> dateList = new ArrayList<>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        if("share".equals(viewType)){
            if(StringUtils.isEmpty(sharedId)) {
                List<String> shareIdList = new ArrayList<>();
                //查出所有共享人
                List<Map<String, String>> shareUserList =  this.getShareOwner(userId,corpId,token);
                for(Map<String, String> map : shareUserList) {
                    shareIdList.add(map.get("userId"));
                }
                List<String> shareCalFieldValue = new ArrayList<>();
                List<String> cates = new ArrayList<>();
                List<String> shareCatFieldValue = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                if(CollectionUtils.isNotEmpty(shareIdList)) {
                    shareCalFieldValue = this.getSharedFieldValue(userId,shareIdList, "1",corpId,token);//共享日程
                    shareCatFieldValue = this.getSharedFieldValue(userId,shareIdList, "2",corpId,token);//共享分类
                    cates = this.calendarCategoryDao.getAllSharedCategory(shareIdList, shareCatFieldValue,source);
                    if(cates.isEmpty()){
                        cates.add("");
                    }
                    list = this.calendarDao.findAllSharedOaCalendar("%%",shareIdList,shareCalFieldValue,cates,startDate,endDate,corpId);
                }
            }else {
                List<String> shareCalFieldValue = this.getFieldValue(userId,sharedId, "1", corpId,token);//共享日程
                List<String> shareCatFieldValue = this.getFieldValue(userId,sharedId, "2", corpId,token);//共享分类
                List<String> cates = new ArrayList<>();
                List<String> source = this.getSysSources(corpId);
                cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue, source);
                if(cates.isEmpty()){
                    cates.add("");
                }
                list = this.calendarDao.findSharedOaCalendar(sharedId,shareCalFieldValue,cates,startDate,endDate,corpId);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            List<String> sysCate = new ArrayList<>();
            if("1".equals(leaderOrSub)) {
                sysCate = calendarCategoryDao.getCalendarSingleCate(Arrays.asList(userId.split(",")));
            }
            if(sysCate.isEmpty()){
                sysCate.add("1");
            }
            if("1".equals(leaderOrSub)) {
                list = this.calendarDao.findMineOaCalendarNoSys("%%",Arrays.asList(userId.split(",")), startDate, endDate, corpId, sysCate);
                if(CollectionUtils.isNotEmpty(partFieldValue)) {
                    List<Calendar> partList = this.calendarDao.findMinePartOaCalendar("%%", partFieldValue, startDate, endDate, corpId, sysCate);
                    if(CollectionUtils.isNotEmpty(partList)) {
                        list.addAll(partList);
                    }
                }
            }else {
                list = this.calendarDao.findMineOaCalendar("%%",userId, partFieldValue, startDate, endDate, corpId, sysCate);
            }
        }
        if(list !=null && !list.isEmpty()){
            for(int i=0;i<list.size();i++){
                Calendar calendar = list.get(i);
                if(calendar != null){
                    String calendarStart = CalendarUtils.getStrByDate(calendar.getStartDate(), "yyyy-MM-dd");
                    String calendarEnd = calendar.getEndDate()==null ? calendarStart : CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
                    int flag = CalendarUtils.compareDateStr(calendarStart, start);
                    int startFlag = CalendarUtils.compareDateStr(calendarStart, end);
                    int flagEnd = CalendarUtils.compareDateStr(calendarEnd, start);
                    int endFlag = CalendarUtils.compareDateStr(calendarEnd, end);
                    if((flag!=2 && startFlag!=1)||(flagEnd!=2 && endFlag!=1)){
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", calendarStart);
                        map.put("endDate", calendarEnd);
                        dateList.add(map);
                    }
                    if(!"no".equals(calendar.getDuplicateType()) && "1".equals(calendar.getIsMain()) && endFlag!=1){
                        List<Map<String, String>> repeatList ;
                        repeatList = this.getDataMsg(calendar.getDuplicateType(), calendar.getDuplicateInterval(), calendar.getDuplicateEndType(), calendar.getDuplicateEndTypeValue(), calendarStart, calendarEnd, end,calendar.getWeekMonthDuplicateType());
                        if(repeatList!= null && !repeatList.isEmpty()){
                            List<CalendarDelete> deletes = this.calendarDeleteDao.findByBelong(calendar.getId(), endDate);
                            String delFlag = "";
                            for(int j=0;j<repeatList.size();j++){
                                Map<String, String> date = repeatList.get(j);
                                String mapStart = date.get("startDate");
                                for (CalendarDelete delete : deletes) {
                                    if(delete != null){
                                        delFlag = delete.getDeleteType();
                                        if("current".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(mapStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }else if("after".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(mapStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }
                                        if(flag == 0){
                                            break;
                                        }
                                    }
                                }
                                if(flag==0 && "current".equals(delFlag)){
                                    continue;
                                }else if(flag==0 && "after".equals(delFlag)){
                                    break;
                                }
                                int flag1 = CalendarUtils.compareDateStr(mapStart, start);
                                int flag2 = CalendarUtils.compareDateStr(mapStart, end);
                                if(flag1!=2 && flag2!=1){
                                    dateList.add(date);
                                }
                                if(flag2 == 1){
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return dateList;
    }

    /**
     * 获取共享日程("全部") 日程表标识值
     * @param userId
     * @param sharedId
     * @param type
     * @param corpId
     * @param token
     * @return
     */
    private List<String> getSharedFieldValue(String userId,List<String> sharedId, String type, String corpId, String token){
        Map<String,String> textParams = new HashMap<String,String>();
        textParams.put("corpId", corpId);
        textParams.put("userIds",  userId);
        textParams.put("thirdType",  "");
        textParams.put("queryType",  "1");
        textParams.put("token",  token);
        //获取用户,组织id;用于可新建权限,可维护权限范围查询
        List<String> scopeList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        if(!scopeList.isEmpty()){
            scopeList.add(userId);
        }else {
            scopeList.add("");
        }
        //获取用户,组织,群组,岗位id;用于可查看范围查询
        List<String> allIdList = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
        scopeList.addAll(allIdList);

        //获取个人群组
        List<String> groupList = this.getGroupIdList(userId,token);
        scopeList.addAll(groupList);

        List<String> fieldValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select s.fieldDataValue from oa_calendar_scope s ");
        if("1".equals(type)){
            sql.append(" left join oa_calendar o on o.maintainer=s.fieldDataValue or o.viewer=s.fieldDataValue ");
            sql.append(" where ((s.scopeValue in (?1) and o.maintainer=s.fieldDataValue) or (s.scopeValue in (?1) and o.viewer=s.fieldDataValue)) and o.calendar_owner in (?2) ");
            fieldValue = super.getEntityManager().createNativeQuery(sql.toString()).setParameter(1, scopeList).setParameter(2, sharedId).getResultList();
        }else if("2".equals(type)){
            sql.append(" left join oa_calendar_category o on o.maintainer=s.fieldDataValue or o.viewer=s.fieldDataValue or o.creator=s.fieldDataValue ");
            sql.append(" where ((s.scopeValue in (?1) and (o.maintainer=s.fieldDataValue or o.creator=s.fieldDataValue)) or (s.scopeValue in (?1) and o.viewer=s.fieldDataValue)) and o.createdBy in (?2) ");
            fieldValue = super.getEntityManager().createNativeQuery(sql.toString()).setParameter(1, scopeList).setParameter(2, sharedId).getResultList();
        }else{
            fieldValue = this.popUserScopeUtilService.getFieldDataValue("oa_calendar_scope", scopeList, "oa_calendar", "participant");
        }
        if(fieldValue.isEmpty()){
            fieldValue.add("");
        }
        return fieldValue;
    }

    /**
     * 获取领导/下属/共享("个人") 3种日程表标识值（共享或参与日程）
     * @param userId
     * @param type(1-共享日程，2-共享分类，3-参与日程)
     * @return
     */
    private List<String> getFieldValue(String userId,String sharedId, String type, String corpId, String token){
        Map<String,String> textParams = new HashMap<String,String>();
        textParams.put("corpId", corpId);
        textParams.put("userIds",  userId);
        textParams.put("thirdType",  "");
        textParams.put("queryType",  "1");
        textParams.put("token",  token);
        //获取用户,组织id;用于可新建权限,可维护权限范围查询
        List<String> userIdList = Arrays.asList(userId.split(","));
        List<String> scopeList = new ArrayList<>();
        List<String> list = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        scopeList.addAll(list);
        if(!scopeList.isEmpty()){
            scopeList.addAll(userIdList);
        }else {
            scopeList.add("");
        }
        //获取用户,组织,群组,岗位id;用于可查看范围查询
        List<String> allIdList = new ArrayList<>();
        if(StringUtils.equals("1", type) || StringUtils.equals("2", type)) {
            allIdList = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
        }
        scopeList.addAll(allIdList);
        //获取个人群组
        List<String> groupList = this.getGroupIdList(userId,token);
        scopeList.addAll(groupList);
        List<String> fieldValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select s.fieldDataValue from oa_calendar_scope s ");
        if("1".equals(type)){
            sql.append(" left join oa_calendar o on o.maintainer=s.fieldDataValue or o.viewer=s.fieldDataValue ");
            sql.append(" where ((s.scopeValue in (?1) and o.maintainer=s.fieldDataValue) or (s.scopeValue in (?1) and o.viewer=s.fieldDataValue)) and o.calendar_owner = ?2 ");
            fieldValue = super.getEntityManager().createNativeQuery(sql.toString()).setParameter(1, scopeList).setParameter(2, sharedId).getResultList();
        }else if("2".equals(type)){
            sql.append(" left join oa_calendar_category o on o.maintainer=s.fieldDataValue or o.viewer=s.fieldDataValue or o.creator=s.fieldDataValue ");
            sql.append(" where ((s.scopeValue in (?1) and (o.maintainer=s.fieldDataValue or o.creator=s.fieldDataValue)) or (s.scopeValue in (?1) and o.viewer=s.fieldDataValue)) and o.createdBy = ?2 ");
            fieldValue = super.getEntityManager().createNativeQuery(sql.toString()).setParameter(1, scopeList).setParameter(2, sharedId).getResultList();
        }else{
            fieldValue = this.popUserScopeUtilService.getFieldDataValue("oa_calendar_scope", scopeList, "oa_calendar", "participant");
        }
        if(fieldValue.isEmpty()){
            fieldValue.add("");
        }
        return fieldValue;
    }

    /**
     * 判断该日程是否被共享给当前用户
     * @param calendar
     * @param userId
     * @param corpId
     * @return
     */
    public boolean isView(Calendar calendar,String userId, String corpId, String token){
        Map<String,String> textParams = new HashMap<String,String>();
        textParams.put("corpId", corpId);
        textParams.put("userIds",  userId);
        textParams.put("thirdType",  "");
        textParams.put("queryType",  "1");
        List<String> scopeList  = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        if(!scopeList.isEmpty()){
            scopeList.add(userId);
        }else {
            scopeList.add("");
        }
        StringBuffer sql = new StringBuffer();
        sql.append("select count(id) from oa_calendar_scope s ");
        sql.append("where s.scopeValue in (?1) and s.fieldDataValue in (?2)");
        Query query = super.getEntityManager().createNativeQuery(sql.toString());
        CalendarCategory category = this.calendarCategoryDao.findById(calendar.getCalendarCategory()).get();
        List<String> fieldValue = new ArrayList<>();
        fieldValue.add(StringUtils.null2String(calendar.getViewer()));
        fieldValue.add(StringUtils.null2String(calendar.getMaintainer()));
        fieldValue.add(StringUtils.null2String(category.getViewer()));
        fieldValue.add(StringUtils.null2String(category.getMaintainer()));
        fieldValue.add(StringUtils.null2String(category.getCreator()));
        int count = Integer.parseInt(query.setParameter(1, scopeList).setParameter(2, fieldValue).getSingleResult().toString());
        if(count > 0){
            return true;
        }
        return false;
    }

    /**
     * 获取维护日程权限的日程表标识值(拼接日程事件时判断日程是否可以修改)
     * @param userId
     * @return
     */
    public List<String> getAllMaintainFieldValue(String userId, List<String> sharedId, String corpId, String token){
        Map<String,Object> paramMap = new HashMap<String,Object>();
        List<String> scopeList  = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        if(!scopeList.isEmpty()){
            scopeList.add(userId);
        }else {
            scopeList.add("");
        }
        List<String> allIdList = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
        scopeList.addAll(allIdList);
        //获取个人群组
        List<String> groupList = this.getGroupIdList(userId,token);
        scopeList.addAll(groupList);
        List<String> fieldValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select s.fieldDataValue from oa_calendar_scope s ");
        sql.append("left join oa_calendar o on o.maintainer = s.fieldDataValue ");
        sql.append("left join oa_calendar_category c on c.maintainer = s.fieldDataValue ");
        sql.append("where s.scopeValue in (:scopeList) ");
        paramMap.put("scopeList",scopeList);
        if(CollectionUtils.isNotEmpty(sharedId)){
            sql.append(" and (c.createdBy in (:sharedId) or o.calendar_owner in (:sharedId) )");
            paramMap.put("sharedId",sharedId);
        }

        List<Map> resultList = super.findByListNativeQuery(sql.toString(), "",paramMap);
        if(CollectionUtils.isNotEmpty(resultList)){
            String fieldDataValue;
            for(Map result : resultList){
                fieldDataValue = StringUtils.null2String(result.get("fieldDataValue"));
                if(StringUtils.isNotEmpty(fieldDataValue)){
                    fieldValue.add(fieldDataValue);
                }
            }
        }
        return fieldValue;
    }

    /**
     * 获取维护日程权限的日程表标识值(拼接日程事件时判断日程是否可以修改)
     * @param userId
     * @return
     */
    public List<String> getMaintainFieldValue(String userId, String sharedId, String corpId, String token){
        Map<String,Object> paramMap = new HashMap<String,Object>();
        List<String> scopeList  = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        if(!scopeList.isEmpty()){
            scopeList.add(userId);
        }else {
            scopeList.add("");
        }
        List<String> fieldValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select s.fieldDataValue from oa_calendar_scope s ");
        sql.append("left join oa_calendar o on o.maintainer = s.fieldDataValue ");
        sql.append("left join oa_calendar_category c on c.maintainer = s.fieldDataValue ");
        sql.append("where s.scopeValue in (:scopeList) ");
        paramMap.put("scopeList",scopeList);
        if(StringUtils.isNotBlank(sharedId)){
            sql.append(" and (c.createdBy = :sharedId or o.calendar_owner = :sharedId )");
            paramMap.put("sharedId",sharedId);
        }

        List<Map> resultList = super.findByListNativeQuery(sql.toString(), "",paramMap);
        if(CollectionUtils.isNotEmpty(resultList)){
            String fieldDataValue;
            for(Map result : resultList){
                fieldDataValue = StringUtils.null2String(result.get("fieldDataValue"));
                if(StringUtils.isNotEmpty(fieldDataValue)){
                    fieldValue.add(fieldDataValue);
                }
            }
        }

        return fieldValue;
    }

    /**
     *
     * @param complateType 1:我的日程;2:领导/下属日程;3:共享日程;4:不需要查询当前日程的完成状态
     * @param isComplateId 根据complateType决定,具体代表前台当前日程所在位置,即页面显示的是谁的日程
     * @param calendar
     * @param searchStart
     * @param searchEnd
     * @param viewType
     * @param userId
     * @param corpId
     * @param maintainFieldValue
     * @return
     */
    public String getCalendarInfo(String complateType , String isComplateId ,Calendar calendar,String searchStart,String searchEnd,String viewType,String userId,String corpId,List<String> maintainFieldValue,Map<String,List<CalendarDelete>> deletesMap,Map<String,CalendarCategory> categoryMap,Map<String,List<Calendar>> repeatsMap,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();
        String calendarStart = CalendarUtils.getStrByDate(calendar.getStartDate(), "yyyy-MM-dd");
        String calendarEnd = calendar.getEndDate()==null ? calendarStart : CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
        //拼接日程事件
        String isMain = calendar.getIsMain();

        String duplicateType = calendar.getDuplicateType();
        if(!"no".equals(duplicateType) && "1".equals(isMain)){//主日程拼接重复日程json
            Date startCalendarDate = DateUtils.parseDate(calendarStart);
            Date endCalendarDate = DateUtils.parseDate(calendarEnd);
            Date startSearchDate = DateUtils.parseDate(searchStart);
            Date startEndDate = DateUtils.parseDate(searchEnd);
            if((startCalendarDate.getTime()<=startSearchDate.getTime() && endCalendarDate.getTime()>=startSearchDate.getTime())
                    || (startCalendarDate.getTime()>=startSearchDate.getTime()&&startCalendarDate.getTime()<=startEndDate.getTime())){
                result.append(this.setCalendarJson(complateType,isComplateId,calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,categoryMap,partFinishedMap));
            }

            String duplicateTypeValue = calendar.getDuplicateInterval();//重复间隔值
            String duplicateEndType = calendar.getDuplicateEndType();//重复结束类型
            String duplicateEndTypeValue = calendar.getDuplicateEndTypeValue();//重复结束类型值
            String weekMonthDuplicateType = calendar.getWeekMonthDuplicateType();//周/月重复类型
            List<Map<String, String>> list ;
            list = this.getDataMsg(duplicateType, duplicateTypeValue, duplicateEndType, duplicateEndTypeValue, calendarStart, calendarEnd==""?calendarStart:calendarEnd, searchEnd,weekMonthDuplicateType);

            if(list != null && !list.isEmpty()){
                String startDate = "";
                List<CalendarDelete> deletes = deletesMap.get(calendar.getId());
                //deletes = this.calendarDeleteDao.findByBelong(calendar.getId(), end);
                int flag = 0,flag1 = 0,flag2 = 0;
                String delFlag = "";
                for(int i=0;i<list.size();i++){
                    Map<String, String> map = list.get(i);
                    startDate = map.get("startDate");
                    if(deletes!=null && !deletes.isEmpty()){
                        for(int j=0;j<deletes.size();j++){
                            CalendarDelete delete = deletes.get(j);
                            if(delete != null){
                                delFlag = delete.getDeleteType();
                                if("current".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }else if("after".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }
                                if(flag == 0){
                                    break;
                                }
                            }
                        }
                        if(flag==0 && "current".equals(delFlag)){
                            continue;
                        }else if(flag==0 && "after".equals(delFlag)){
                            break;
                        }
                    }
                    flag1 = CalendarUtils.compareDateStr(searchStart, startDate);
                    flag = CalendarUtils.compareDateStr(searchEnd, startDate);
                    if(flag1!=1 && flag!=2){
                        List<Calendar> repeats = new ArrayList<>();
                        //repeats = this.calendarDao.findCalendarByBelong(calendar.getId(), start, end);
                        repeats = repeatsMap.get(calendar.getId());
                        boolean equal = true;
                        if(repeats!=null && !repeats.isEmpty()){
                            for(int j=0;j<repeats.size();j++){
                                Calendar repeat = repeats.get(j);
                                flag2 = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                if(flag2 == 0){
                                    equal = false;
                                    break;
                                }
                            }
                        }
                        if(equal){
                            result.append(",");
                            result.append(this.setCalendarJson("4",isComplateId, calendar, startDate, map.get("endDate"),"repeat",viewType,userId,corpId,maintainFieldValue,categoryMap,partFinishedMap));
                        }
                    }
                }
            }
        }else if(!"no".equals(duplicateType) && "0".equals(isMain)){//有编辑的子日程，返回回去
            Date startCalendarDate = DateUtils.parseDate(calendarStart);
            Date endCalendarDate = DateUtils.parseDate(calendarEnd);
            Date startSearchDate = DateUtils.parseDate(searchStart);
            Date startEndDate = DateUtils.parseDate(searchEnd);
            if((startCalendarDate.getTime()<=startSearchDate.getTime() && endCalendarDate.getTime()>=startSearchDate.getTime())
                    || (startCalendarDate.getTime()>=startSearchDate.getTime()&&startCalendarDate.getTime()<=startEndDate.getTime())){
                result.append(this.setCalendarJson(complateType,isComplateId,calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,categoryMap,partFinishedMap));
            }
        }else{
            result.append(this.setCalendarJson(complateType,isComplateId,calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,categoryMap,partFinishedMap));
        }
        return result.toString();
    }

    /**
     * 当前日程是否完成，完成、取消完成方法
     * @param isComplate 1 完成日程 0 取消完成
     * @param calendarId 日程id
     * @param startDate 日程开始日期
     * @param endDate 日程结束日期
     * @param userId 完成人Id
     * @param updateComplate 完成类型 current 当前  all 全部
     * @param finishType 完成日程类型 我的  myCalendar  领导 leaderCalendar  共享 shareCalendar
     * @return OperationResult
     */
    public OperationResult complateCalendar(String isComplate,String calendarId, String startDate, String endDate, String userId, String updateComplate, String finishType) {
        Calendar calendar = this.findOne(calendarId);
        //重复类型，no 代表不重复
        String duplicateType = calendar.getDuplicateType();
        //1 主日程  0 子日程
        String isMain = calendar.getIsMain();

        if(StringUtils.isBlank(endDate)){
            endDate = startDate;
        }

        /**修改重复日程**/
        if(!"no".equals(duplicateType)) {

            Date start = new Date();
            Date end = new Date();
            try {
                start = CalendarUtils.getDataByStr(startDate,"yyyy-MM-dd");
                end = CalendarUtils.getDataByStr(endDate,"yyyy-MM-dd");
            } catch (Exception e) {
                LOG.error("日期转换异常",e);
                return OperationResult.buildFailureResult("保存失败");
            }

            Date calendarStartDate = calendar.getStartDate();

            /**日期不相等，主日程,过来的是子日程数据，需要新增子日程**/
            if("1".equals(isMain) && CalendarUtils.compareDate(start,calendarStartDate)!=0 ){

                Calendar subCalendar = this.addSubCalendar(calendar,start,end);
                this.complateOrCancelCalendar(isComplate,subCalendar,userId,updateComplate,finishType);
            }else{
                /**已有子日程或者主日程**/
                this.complateOrCancelCalendar(isComplate,calendar,userId,updateComplate,finishType);
            }

        } else {
            /**修改非重复日程**/
            this.complateOrCancelCalendar(isComplate,calendar,userId,updateComplate,finishType);
        }
        return OperationResult.buildSuccessResult("保存成功");
    }

    /**
     * 创建重复日程下的子日程
     * @param mainCalendar 主日程实体类
     * @param startDate 子日程开始日期（Date）
     * @param endDate 子日程结束日期（Date）
     * @return subCalendar 子日程实体类
     *
     */
    public Calendar addSubCalendar(Calendar mainCalendar, Date startDate, Date endDate){
        Calendar subCalendar = new Calendar();
        BeanUtils.copyProperties(mainCalendar, subCalendar);
        subCalendar.setId(null);
        subCalendar.setIsMain("0");
        subCalendar.setBelongCalendar(mainCalendar.getId());
        subCalendar.setStartDate(startDate);
        subCalendar.setEndDate(endDate);
        super.save(subCalendar);
        return subCalendar;
    }

    /**
     * 完成、取消完成日程
     * @param isComplate 1 完成日程 0 取消完成
     * @param calendar 日程实体类
     * @param userId 完成人Id
     * @param updateComplate 完成类型 current 当前  all 全部
     * @param finishType 完成日程类型 我的  myCalendar  领导 leaderCalendar  共享 shareCalendar
     *
     */
    public void complateOrCancelCalendar(String isComplate,Calendar calendar, String userId, String updateComplate, String finishType){
        String calendarId = calendar.getId();
        String calendarOwner = calendar.getCalendarOwner();
        //完成日程
        if("1".equals(isComplate)){
            if("myCalendar".equals(finishType) || "leaderCalendar".equals(finishType)){

                //我的日程、领导日程下，日程所属人不是我，我就是参与人
                if(!userId.equals(calendarOwner)){
                    //只新增我的完成数据
                    saveCalendarFinished(calendarId,userId);
                }else{
                    //日程所属人是我，完成要判断是完成我的还是所有人的
                    if("current".equals(updateComplate)){
                        //完成我的
                        saveCalendarFinished(calendarId,userId);
                    }else{
                        //完成所有人的
                        List<String> partList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope", "oa_calendar", "participant", calendar.getParticipant());
                        partList.add(userId);
                        for (String partId : partList) {
                            saveCalendarFinished(calendarId,partId);
                        }
                    }
                }
            }else{
                //共享日程下，不存在参与日程

                if("current".equals(updateComplate)){
                    //完成我的
                    saveCalendarFinished(calendarId,calendarOwner);
                }else{
                    //完成所有人的
                    List<String> partList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope", "oa_calendar", "participant", calendar.getParticipant());
                    partList.add(calendarOwner);
                    for (String partId : partList) {
                        saveCalendarFinished(calendarId,partId);
                    }
                }

            }

        }else{//取消完成
            if("myCalendar".equals(finishType) || "leaderCalendar".equals(finishType)){

                //我的日程、领导日程下，日程所属人不是我，我就是参与人
                if(!userId.equals(calendarOwner)){
                    //只删除我的完成数据
                    calendarFinishedDao.deleteCalendarFinishedsByCalendarIdAndPartId(calendarId, userId);
                }else{
                    //日程所属人是我，取消完成取消所有人，删除该日程所有人数据
                    calendarFinishedDao.deleteCalendarFinishedsByCalendarId(calendarId);
                }
            }else{
                //共享日程下，不存在参与日程,取消完成，取消所有人的完成数据
                calendarFinishedDao.deleteCalendarFinishedsByCalendarId(calendarId);

            }
        }
    }

    /**
     * 日程完成 相关数据保存 calendar_finish
     * @param  calendarId 日程id
     * @param  userId  完成人Id
     *
     */
    public void saveCalendarFinished(String calendarId, String userId){
        CalendarFinished calendarFinished = new CalendarFinished();
        calendarFinished.setCalendarId(calendarId);
        calendarFinished.setPartId(userId);
        calendarFinishedDao.save(calendarFinished);
    }


    /**
     * 拼接日程时间的json数据
     * @param calendar
     * @param startDate
     * @param endDate
     * @param repeatType
     * @param viewType
     * @param userId
     * @param corpId
     * @return
     */
    private String setCalendarJson(String complateType, String isComplateId,Calendar calendar, String startDate, String endDate,String repeatType,String viewType,String userId,String corpId,List<String> maintainFieldValue,Map<String,CalendarCategory> categorysMap,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();

        List<String> morePartList = new ArrayList<>();
        List<String> userList = Arrays.asList(userId.split(","));

        //查询当前用户是否已经完成该日程,如果complateType为4是不需要查询完成状况
        boolean isComplate = false;
        if(!StringUtils.equals(complateType, "4")) {
            // 指定日程标记完成参与人ID集合
            List<String> partIdList = calendarFinishedDao.findPartId(calendar.getId());
            // 20210830 日程标记功能：判断当前用户是否标记完成日程
            if ("share".equals(viewType)) {
                // 共享日程判断日程是否完成判断的是创建人是否完成
                if (null != partIdList && partIdList.size() > 0) {
                    if (partIdList.contains(calendar.getCalendarOwner())) {
                        isComplate = true;
                    }
                }
                if(StringUtils.null2String(calendar.getCalendarCategory()).contains("_part")) {//参与日程
                    if (null != partIdList && partIdList.size() > 0) {
                        for(String partId : userList){
                            if (partIdList.contains(partId)) {
                                isComplate = true;
                                break;
                            }
                        }

                    }
                }
            } else {
                if (null != partIdList && partIdList.size() > 0) {
                    for(String partId : userList){
                        if (partIdList.contains(partId)) {
                            isComplate = true;
                            break;
                        }
                    }
                }
            }
            // isComplate = StringUtils.equals("1", calendar.getIsComplate())?true:false;
            if(StringUtils.isNotEmpty(calendar.getStartDate().toString())) {
                String calendarStart = DateUtils.formatDate(calendar.getStartDate(),"yyyy-MM-dd");
                if(!StringUtils.equals(calendarStart, startDate)) {
                    isComplate = false;
                }
            }
        }

        boolean isRealCreator = StringUtils.equals(StringUtils.null2String(calendar.getCreatedBy()), userId);
        result.append("{mainId:'" + calendar.getId() + "',"
                + "title:'" + calendar.getTitle().replace("\\","\\\\").replace("'","\\'").replace("[","flexbracketB").replace("]","flexbracketE") + "'," +
                "secdatacode:'"+calendar.getSecdatacode()+"',"
                + "isMain:'" + calendar.getIsMain() + "',"
                + "calendarOwner:'" + calendar.getCalendarOwner() + "',"
                + "isComplate:'" + isComplate + "',"
                + "content:'" + (calendar.getContent() == null ? "" : calendar.getContent().replace("\\","\\\\").replace("'","\\'")).replace("[","flexbracketB").replace("]","flexbracketE") + "',"
                + "isRealCreator:'" + isRealCreator + "'," //是否是日程创建人
                + "address:'" + (calendar.getAddress() == null ? "" : calendar.getAddress().replace("\\","\\\\").replace("'","\\'")).replace("[","flexbracketB").replace("]","flexbracketE") + "',"
                + "participant2:'" + calendar.getParticipant() + "',"
                + "isDuplicate:'" + calendar.getDuplicateType() + "',");
        if("1".equals(calendar.getIsAllDay())){//全天日程
            result.append("allDay:true,"
                    + "start:'" + startDate + "',"
                    + "startTime:'"+ 0 +"'," // 全天日程开始时间设置为0，显示在上午区域中
                    + "startWeek: '" + 0 +"',"  // 全天日程开始时间设置为0，标题前不显示时间
                    + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm: '"+ 1 +"',"); // 全天日程默认显示在上午
        } else if (StringUtils.isNotBlank(calendar.getSetTimeFlag())) { // 上午/下午模式
            String startTime = "";
            String endTime = "";
            int startTimeIntVal=0;
            int endTimeIntVal=0;
            if("1".equals(calendar.getSetTimeFlag())){
                startTime="09:00";
                startTimeIntVal=32400;
                endTime = "12:00";
                endTimeIntVal=43200;
            }else{
                startTime="14:00";
                startTimeIntVal=50400;
                endTime = "18:00";
                endTimeIntVal=64800;
            }
            result.append("allDay:false,"
                    + "start:'" + startDate + "T" + startTime + "',"
                    + "end:'" + endDate + "T" + endTime + "',"
                    + "startTime:'"+ startTimeIntVal +"'," //
                    + "endTime:'"+ endTimeIntVal +"'," //
                    + "startWeek: '" + 0 +"',"  // 上午/下午模式日程开始时间设置为0，标题前不显示时间
                    + "amOrPm:'" + 1 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm: '"+ (Integer.parseInt(calendar.getSetTimeFlag())<=0? "0":"1") +"',"); // 上午/下午模式中日程所处位置
        } else{
            String startTime = CalendarUtils.getTime(calendar.getStartTime());
            String endTime = CalendarUtils.getTime(calendar.getEndTime());
            result.append("allDay:false,start:'" + startDate + "T" + startTime + "',"
                    + "end:'" + endDate + "T" + endTime + "',"
                    + "startTime:'"+ calendar.getStartTime() +"',"
                    + "startWeek: '" + startDate + " " + startTime + "'," // 日程开始时间，用于标题前显示
                    + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                    + "isAmOrPm:'"+(Integer.parseInt(startTime.split(":")[0]) >= 12? "0": "1")+"',");
        }
        if("repeat".equals(repeatType) || "0".equals(calendar.getIsMain())){
            result.append("repeat:'1',");
            if("1".equals(calendar.getIsMain())){
                result.append("id:'" + calendar.getId() + "',");
            }else{
                result.append("id:'" + calendar.getBelongCalendar() + "',");
            }
            result.append("dragable:false,");
        }else{
            result.append("repeat:'0',").append("id:'" + calendar.getId() + "',");
        }
        CalendarCategory category = new CalendarCategory();
        if(StringUtils.null2String(calendar.getCalendarCategory()).contains("_part")) {//参与日程
            List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
            if (CollectionUtils.isNotEmpty(categorys)) {
                category = categorys.get(0);
            }
            super.detach(calendar);
            calendar.setCalendarCategory(calendar.getCalendarCategory().split("_")[0]);

            List<String> scopeValueList = calendarDao.selectScopeValueList(calendar.getParticipant());
            for(String partUserId : userList){
                if(scopeValueList.contains(partUserId)){
                    morePartList.add(partUserId);
                }
            }

            result.append("isPart:'1',");
        }else {
            if(!userList.contains(calendar.getCalendarOwner()) && !"share".equals(viewType)){//参与日程
                List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
                if (CollectionUtils.isNotEmpty(categorys)) {
                    category = categorys.get(0);
                }
                List<String> scopeValueList = calendarDao.selectScopeValueList(calendar.getParticipant());
                for(String partUserId : userList){
                    if(scopeValueList.contains(partUserId)){
                        morePartList.add(partUserId);
                    }
                }

                result.append("isPart:'1',");
            }else{
                //category = this.calendarCategoryDao.getCategoryById(calendar.getCalendarCategory(), corpId);
                category = categorysMap.get(calendar.getCalendarCategory());
            }
        }
        if(category == null) {
            return "";
        }
        if("share".equals(viewType)){
            String fieldValue1 = StringUtils.null2String(calendar.getMaintainer());
            String fieldValue2 = StringUtils.null2String(category.getMaintainer());
            if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2))){
                result.append("isMaintain:'1',");
                if("repeat".equals(repeatType)){
                    if("1".equals(calendar.getIsMain())){
                        result.append("showEditMsg:'1',");
                    }else{
                        Calendar main = this.calendarDao.findById(calendar.getBelongCalendar()).get();
                        CalendarCategory cate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                        fieldValue1 = StringUtils.null2String(main.getMaintainer());
                        fieldValue2 = StringUtils.null2String(cate.getMaintainer());
                        if(maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2)){
                            result.append("showEditMsg:'1',");
                        }
                    }
                }
            }else{
                result.append("isMaintain:'0',");
                if(!"repeat".equals(viewType) && "1".equals(calendar.getIsMain())){
                    result.append("dragable:false,");
                }
            }
        }
        if("-1".equals(calendar.getIsMain())) {
            result.append("isMaintain:'-1',");
        }else if("-2".equals(calendar.getIsMain())) {
            result.append("isMaintain:'-2',");
        }
        result.append("classfiy:'" + category.getId() + "',");
        result.append("classfiyName:'" + category.getName() + "',");
        String syncId = StringUtils.null2String(calendar.getSyncId());
        result.append("syncId:'" + syncId + "',");
        if(calendar.getDegreeOfImportance() == null) {
            result.append("degreeOfImportance:'1',");
        }else {
            result.append("degreeOfImportance:'"+calendar.getDegreeOfImportance()+"',");
        }
        if(isComplate){
            result.append("color:'#3f3f3f'").append("}");
        }else {
            result.append("color:'" + category.getBackColor() + "'").append("}");
        }

//        String resultStr = result.toString();
//        if(CollectionUtils.isNotEmpty(morePartList)){
//            Map<String,String> resultMap = (Map<String, String>) JSON.parse(resultStr);
//            resultStr = "";
//            for(String partUserId : morePartList){
//                resultMap.put("showOwner",partUserId);
//                resultStr = resultStr+","+JSON.toJSONString(resultMap);;
//            }
//            resultStr = resultStr.substring(1);
//        }


        return result.toString();
    }


    /**
     * 处理重复类型的间隔值(返回值包括主日程日期)
     * 备注：时间格式统一为xxxx-xx-xx
     * @param duplicateType:重复类型
     * @param duplicateTypeValue:重复类型值
     * @param duplicateEndType:重复结束类型
     * @param duplicateEndTypeValue:重复结束类型值,
     * @param startDate:开始时间
     * @param endDate:结束时间
     * @param searchEndDate:查询日程结束时间
     * @return: List<Map<String,String>>集合,map中的key：startDate表示开始时间，endDate表示结束时间
     */
    public List<Map<String,String>> getDataMsg(String duplicateType,String duplicateTypeValue,String duplicateEndType,String duplicateEndTypeValue,
                                               String startDate,String endDate,String searchEndDate,String weekMonthDuplicateType){
        List<Map<String, String>> list = new ArrayList<>();
        //字符串相隔天数
        int intervals = CalendarUtils.countDateStrDays(startDate, endDate, "yyyy-MM-dd");
        if("day".equals(duplicateType)){
            int days = Integer.parseInt(duplicateTypeValue) + intervals;
            if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                if("endTime".equals(duplicateEndType)){
                    //重复结束时间和搜索结束时间比较
                    int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                    //重复结束时间小于搜索结束时间
                    if(result == 2){
                        searchEndDate = duplicateEndTypeValue;
                    }
                }
                int flag = 0 ;
                while(true){
                    startDate = CalendarUtils.addDays(startDate, days, "yyyy-MM-dd");
                    //日程开始时间和搜索时间结束值比较
                    flag = CalendarUtils.compareDateStr(startDate, searchEndDate);
                    //日程开始时间小于、等于搜索结束时间
                    if(flag==0 || flag==2){
                        endDate = CalendarUtils.addDays(startDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", startDate);
                        map.put("endDate", endDate);
                        list.add(map);
                    }else{
                        break;
                    }
                }
            }else{//重复次数
                int i = 1,num = Integer.parseInt(duplicateEndTypeValue),flag = 0;
                while(i <= num){
                    startDate = CalendarUtils.addDays(startDate, days, "yyyy-MM-dd");
                    flag = CalendarUtils.compareDateStr(startDate, searchEndDate);
                    if(flag==0 || flag==2){
                        endDate = CalendarUtils.addDays(startDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", startDate);
                        map.put("endDate", endDate);
                        list.add(map);
                        i++;
                    }else{
                        break;
                    }
                }
            }
        }else if("week".equals(duplicateType)){
            if(StringUtils.isNotBlank(weekMonthDuplicateType)) {//处理新数据
                try {
                    char[] duplicateValueArr = duplicateTypeValue.toCharArray();
                    if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                        if("endTime".equals(duplicateEndType)){
                            int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                            if(result == 2){
                                searchEndDate = duplicateEndTypeValue;
                            }
                        }
                        //找到开始时间所在周周一
                        String nextDate = CalendarUtils.getWeekFirstDayStr(startDate);
                        //给开始时间加上"weekMonthDuplicateType"周
                        nextDate = CalendarUtils.addDays(nextDate, 7*Integer.parseInt(weekMonthDuplicateType), "yyyy-MM-dd");
                        while(true){
                            //判断是否进行循环
                            boolean continueRepeat = true;
                            //存放周情况下，选中的星期几
                            int lastWeekDay=0;
                            int flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                            if(flag==0||flag==2){//在时间范围内
                                String repeatDate = nextDate;
                                for(char chooseWeekDay : duplicateValueArr){
                                    lastWeekDay = Integer.parseInt(String.valueOf(chooseWeekDay));
                                    nextDate = CalendarUtils.addDays(repeatDate, lastWeekDay-1, "yyyy-MM-dd");
                                    flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                                    if(flag==0||flag==2){
                                        endDate = CalendarUtils.addDays(nextDate, intervals, "yyyy-MM-dd");
                                        Map<String, String> map = new HashMap<>();
                                        map.put("startDate", nextDate);
                                        map.put("endDate", endDate);
                                        list.add(map);
                                    }else{
                                        continueRepeat = false;
                                        break;
                                    }
                                }
                                if(continueRepeat){
                                    nextDate = CalendarUtils.addDays(repeatDate, 7*(Integer.parseInt(weekMonthDuplicateType)), "yyyy-MM-dd");
                                }else{
                                    break;
                                }
                            }else{
                                break;
                            }
                        }
                    }else{//重复次数
                        int i = 1,num = Integer.parseInt(duplicateEndTypeValue);
                        boolean modal = false;
                        //找到开始时间所在周周一
                        String nextDate = CalendarUtils.getWeekFirstDayStr(startDate);
                        //给开始时间加上"weekMonthDuplicateType"周
                        nextDate = CalendarUtils.addDays(nextDate, 7*Integer.parseInt(weekMonthDuplicateType), "yyyy-MM-dd");
                        while(i <= num){
                            int flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                            //判断是否进行循环
                            boolean continueRepeat = true;
                            //存放周情况下，选中的星期几
                            int lastWeekDay=0;
                            //在时间范围内
                            if(flag==0||flag==2){
                                String repeatDate = nextDate;
                                for(char chooseWeekDay : duplicateValueArr){
                                    lastWeekDay = Integer.parseInt(String.valueOf(chooseWeekDay));
                                    nextDate = CalendarUtils.addDays(repeatDate, lastWeekDay-1, "yyyy-MM-dd");
                                    flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                                    if(flag==0||flag==2){
                                        endDate = CalendarUtils.addDays(nextDate, intervals, "yyyy-MM-dd");
                                        Map<String, String> map = new HashMap<>();
                                        map.put("startDate", nextDate);
                                        map.put("endDate", endDate);
                                        list.add(map);
                                    }else{
                                        continueRepeat = false;
                                        break;
                                    }
                                }
                                if(continueRepeat){
                                    nextDate = CalendarUtils.addDays(repeatDate, 7*(Integer.parseInt(weekMonthDuplicateType)), "yyyy-MM-dd");
                                }else{
                                    break;
                                }
                            }else{
                                break;
                            }
                            i++;
                        }

                    }
                }catch(Exception e) {
                    LOG.error("获取重复日程值失败",e);
                }
            }else {//处理旧数据
                list = this.getOldRepeatCalendarDataList(duplicateType, duplicateTypeValue, duplicateEndType, duplicateEndTypeValue,
                        searchEndDate, startDate, endDate, intervals);
            }
        }else if("month".equals(duplicateType)){
            if(StringUtils.isNotBlank(weekMonthDuplicateType)) {//处理新数据
                String[] valueList = weekMonthDuplicateType.split("在");
                String selectValue = valueList[0];//重复间隔数
                String[] radioList = valueList[1].split("month");
                String radioType = radioList[1];//月的第几个单选 1;xx日2;第x周的周x3;最后一周的周x
                if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                    String repeatDate = startDate;
                    int weekNumber = 1;//周数
                    int weekDateNumber = 1;//周x
                    int maxWeekNumber = 1;//当月最大周数
                    if("endTime".equals(duplicateEndType)){
                        int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                        if(result == 2){
                            searchEndDate = duplicateEndTypeValue;
                        }
                    }

                    if(StringUtils.equals("1", radioType)) {//月 第几日 下
                        //设置第一次重复的时间
                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                        //第一次循环日期
                        repeatDate = CalendarUtils.setDayLimit(repeatDate, radioList[0].replace("日", "").trim(), "yyyy-MM-dd");
                    }else if(StringUtils.equals("2", radioType) || StringUtils.equals("3",radioType)) {// 月 周 下
                        //设置开始日期所在月份的第一天
                        String firstDayOfStartMonth = CalendarUtils.setDay(startDate, "1", "yyyy-MM-dd");
                        //第一个循环日期月的第一天
                        firstDayOfStartMonth = CalendarUtils.addMonthsLimit(firstDayOfStartMonth,"yyyy-MM-dd",Integer.parseInt(selectValue));

                        //获取周数
                        if(StringUtils.equals("2", radioType)) {
                            weekNumber = Integer.parseInt(Character.toString(radioList[0].charAt(1)));
                        }else {
                            //获取最后一周
                            weekNumber = CalendarUtils.getWeekOfMonth(firstDayOfStartMonth.split("-")[0],firstDayOfStartMonth.split("-")[1]);
                        }
                        weekDateNumber = this.revertWeekNumber(radioList[0]);
                        java.util.Calendar cal = java.util.Calendar.getInstance();
                        cal.setFirstDayOfWeek(java.util.Calendar.MONDAY);
                        cal.setTime(CalendarUtils.getDataByStr(firstDayOfStartMonth, "yyyy-MM-dd"));
                        cal.set(java.util.Calendar.WEEK_OF_MONTH, weekNumber);
                        cal.set(java.util.Calendar.DAY_OF_WEEK, weekDateNumber == 7 ? 1 : weekDateNumber+1);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        //第一次循环日期
                        repeatDate = sdf.format(cal.getTime());
                    }
                    while(true){
                        int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                        if(flag==0 || flag==2){
                            endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                            Map<String, String> map = new HashMap<>();
                            map.put("startDate", repeatDate);
                            map.put("endDate", endDate);
                            list.add(map);

                            if(StringUtils.equals("1", radioType)) {
                                repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                repeatDate = CalendarUtils.setDayLimit(repeatDate, radioList[0].replace("日", "").trim(), "yyyy-MM-dd");
                            }else if(StringUtils.equals("2", radioType) || StringUtils.equals("3", radioType)) {//重新计算下一次循环在那一月的第几天
                                java.util.Calendar cal = java.util.Calendar.getInstance();
                                cal.setFirstDayOfWeek(java.util.Calendar.MONDAY);

                                if(StringUtils.equals("3", radioType)) {
                                    //最后一周，需要把日期调整到当前周第一天，防止跨月
                                    repeatDate = CalendarUtils.getWeekFirstDay(repeatDate);
                                    repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                    weekNumber = CalendarUtils.getWeekOfMonth(repeatDate.split("-")[0],repeatDate.split("-")[1]);
                                }

                                if(StringUtils.equals("2", radioType)) {
                                    //第一周，需要把日期调整到当前周最后一天，防止跨月
                                    if(weekNumber==1){
                                        repeatDate = CalendarUtils.getWeekLastDay(repeatDate);
                                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                    }else{
                                        repeatDate = CalendarUtils.getWeekFirstDay(repeatDate);
                                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                        //周数超过下个月的最大周，直接默认最后一个月
                                        if(weekNumber>4){
                                            maxWeekNumber = CalendarUtils.getWeekOfMonth(repeatDate.split("-")[0],repeatDate.split("-")[1]);
                                            if(maxWeekNumber<weekNumber){
                                                weekNumber = maxWeekNumber;
                                            }
                                        }
                                    }
                                }

                                cal.setTime(CalendarUtils.getDataByStr(repeatDate, "yyyy-MM-dd"));
                                cal.set(java.util.Calendar.WEEK_OF_MONTH, weekNumber);
                                cal.set(java.util.Calendar.DAY_OF_WEEK, weekDateNumber == 7 ? 1 : weekDateNumber+1);
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                repeatDate = sdf.format(cal.getTime());

                            }
                        }else{
                            break;
                        }
                    }
                }else{//重复次数
                    int i = 0,num = Integer.parseInt(duplicateEndTypeValue);
                    //设置开始日期所在月份的第一天
                    String firstDayOfStartMonth = CalendarUtils.setDay(startDate, "1", "yyyy-MM-dd");
                    //第一个循环日期月的第一天
                    firstDayOfStartMonth = CalendarUtils.addMonthsLimit(firstDayOfStartMonth,"yyyy-MM-dd",Integer.parseInt(selectValue));
                    String repeatDate = startDate;
                    int weekNumber = 1;//周数
                    int weekDateNumber = 1;//周x
                    int maxWeekNumber = 1;//时间内的最大周数
                    if(StringUtils.equals("1", radioType)) {
                        //第一次重复日期
                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                        repeatDate = CalendarUtils.setDayLimit(repeatDate, radioList[0].replace("日", "").trim(), "yyyy-MM-dd");
                    }else if(StringUtils.equals("2", radioType)) {
                        weekNumber = Integer.parseInt(Character.toString(radioList[0].charAt(1)));
                        weekDateNumber = this.revertWeekNumber(radioList[0].toString().substring(4));
                        java.util.Calendar cal = java.util.Calendar.getInstance();
                        cal.set(java.util.Calendar.YEAR,Integer.parseInt(firstDayOfStartMonth.split("-")[0]));
                        cal.set(java.util.Calendar.MONTH,Integer.parseInt(firstDayOfStartMonth.split("-")[1])-1);
                        cal.set(java.util.Calendar.WEEK_OF_MONTH, weekNumber);
                        cal.set(java.util.Calendar.DAY_OF_WEEK, weekDateNumber == 7 ? 1 : weekDateNumber+1);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        repeatDate = sdf.format(cal.getTime());
                        if(Integer.parseInt(firstDayOfStartMonth.split("-")[1]) != Integer.parseInt(repeatDate.split("-")[1])) {
                            repeatDate = CalendarUtils.getLastDayOfMonth(firstDayOfStartMonth, "yyyy-MM-dd");
                        }
                    }else {//最后一周的情况
                        java.util.Calendar cal = java.util.Calendar.getInstance();
                        cal.setFirstDayOfWeek(java.util.Calendar.MONDAY);
                        weekNumber = CalendarUtils.getWeekOfMonth(firstDayOfStartMonth.split("-")[0],firstDayOfStartMonth.split("-")[1]);
                        weekDateNumber = this.revertWeekNumber(radioList[0].toString().substring(4));
                        cal.setTime(CalendarUtils.getDataByStr(firstDayOfStartMonth, "yyyy-MM-dd"));
                        cal.set(java.util.Calendar.WEEK_OF_MONTH, weekNumber);
                        cal.set(java.util.Calendar.DAY_OF_WEEK, weekDateNumber == 7 ? 1 : weekDateNumber+1);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        repeatDate = sdf.format(cal.getTime());
                    }

                    while(i < num){
                        int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                        if(flag==0 || flag==2){
                            endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                            Map<String, String> map = new HashMap<>();
                            map.put("startDate", repeatDate);
                            map.put("endDate", endDate);
                            list.add(map);
                            i++;
                            if(StringUtils.equals("1", radioType)) {
                                repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                repeatDate = CalendarUtils.setDayLimit(repeatDate, radioList[0].replace("日", "").trim(), "yyyy-MM-dd");
                            }else if(StringUtils.equals("2", radioType) || StringUtils.equals("3", radioType)) {//重新计算下一次循环在那一月的第几天
                                java.util.Calendar cal = java.util.Calendar.getInstance();
                                cal.setFirstDayOfWeek(java.util.Calendar.MONDAY);

                                if(StringUtils.equals("3", radioType)) {
                                    //最后一周，需要把日期调整到当前周第一天，防止跨月
                                    repeatDate = CalendarUtils.getWeekFirstDay(repeatDate);
                                    repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                    weekNumber = CalendarUtils.getWeekOfMonth(repeatDate.split("-")[0],repeatDate.split("-")[1]);
                                }


                                if(StringUtils.equals("2", radioType)) {
                                    //第一周，需要把日期调整到当前周最后一天，防止跨月
                                    if(weekNumber==1){
                                        repeatDate = CalendarUtils.getWeekLastDay(repeatDate);
                                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                    }else{
                                        repeatDate = CalendarUtils.getWeekFirstDay(repeatDate);
                                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",Integer.parseInt(selectValue));
                                        //周数超过下个月的最大周，直接默认最后一个月
                                        if(weekNumber>4){
                                            maxWeekNumber = CalendarUtils.getWeekOfMonth(repeatDate.split("-")[0],repeatDate.split("-")[1]);
                                            if(maxWeekNumber<weekNumber){
                                                weekNumber = maxWeekNumber;
                                            }
                                        }
                                    }
                                }


                                cal.setTime(CalendarUtils.getDataByStr(repeatDate, "yyyy-MM-dd"));
                                cal.set(java.util.Calendar.WEEK_OF_MONTH, weekNumber);
                                cal.set(java.util.Calendar.DAY_OF_WEEK, weekDateNumber == 7 ? 1 : weekDateNumber+1);
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                repeatDate = sdf.format(cal.getTime());

                            }
                        }else{
                            break;
                        }
                    }
                }
            }else {//处理老数据
                list = this.getOldRepeatCalendarDataList(duplicateType, duplicateTypeValue, duplicateEndType, duplicateEndTypeValue,
                        searchEndDate, startDate, endDate, intervals);
            }
        }else if("year".equals(duplicateType)){
            if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                if("endTime".equals(duplicateEndType)){
                    int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                    if(result == 2){
                        searchEndDate = duplicateEndTypeValue;
                    }
                }
                String repeatDate = CalendarUtils.setMonthAndDay(startDate, duplicateTypeValue, "yyyy-MM-dd");
                repeatDate = CalendarUtils.addYears(repeatDate, 1, "yyyy-MM-dd");
                while(true){
                    int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                    if(flag==0 || flag==2){
                        endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", repeatDate);
                        map.put("endDate", endDate);
                        list.add(map);
                    }else{
                        break;
                    }
                    repeatDate = CalendarUtils.addYears(repeatDate, 1, "yyyy-MM-dd");
                }
            }else{//重复次数
                int i = 1,num = Integer.parseInt(duplicateEndTypeValue);
                String repeatDate = CalendarUtils.setMonthAndDay(startDate, duplicateTypeValue, "yyyy-MM-dd");
                repeatDate = CalendarUtils.addYears(repeatDate, 1, "yyyy-MM-dd");
                while(i <= num){
                    int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                    if(flag==0 || flag==2){
                        endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", repeatDate);
                        map.put("endDate", endDate);
                        list.add(map);
                        i++;
                    }else{
                        break;
                    }
                    repeatDate = CalendarUtils.addYears(repeatDate, 1, "yyyy-MM-dd");
                }
            }
        }
        return list;
    }

    /**
     * 日程处理旧数据方法
     * @param duplicateType 重复类型
     * @param duplicateTypeValue 重复类型值
     * @param duplicateEndType 结束类型
     * @param duplicateEndTypeValue 结束类型值
     * @param searchEndDate 搜索结束时间
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param intervals 日期间隔值
     *
     *
     */
    public List<Map<String, String>> getOldRepeatCalendarDataList(String duplicateType,String duplicateTypeValue, String duplicateEndType, String duplicateEndTypeValue,
                     String searchEndDate, String startDate, String endDate, int intervals){

        List<Map<String, String>> list = new ArrayList<>();

        if("week".equals(duplicateType)){
            if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                if("endTime".equals(duplicateEndType)){
                    int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                    if(result == 2){
                        searchEndDate = duplicateEndTypeValue;
                    }
                }
                String nextDate = startDate;
                while(true){
                    nextDate = CalendarUtils.addDays(nextDate, 1, "yyyy-MM-dd");
                    Integer weekDay = CalendarUtils.dayForWeek(nextDate, "yyyy-MM-dd");
                    int flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                    if(duplicateTypeValue.indexOf(weekDay.toString())!=-1 && (flag==0||flag==2)){
                        endDate = CalendarUtils.addDays(nextDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", nextDate);
                        map.put("endDate", endDate);
                        list.add(map);
                    }else if(flag == 1){
                        break;
                    }
                }
            }else{//重复次数
                int i = 1,num = Integer.parseInt(duplicateEndTypeValue);
                String nextDate = endDate;
                boolean model = false;
                while(i <= num){
                    for(int k = 0;k<7;k++) {
                        nextDate = CalendarUtils.addDays(nextDate, 1, "yyyy-MM-dd");
                        int flag = CalendarUtils.compareDateStr(nextDate, searchEndDate);
                        if(flag==0 || flag==2){
                            Integer weekDay = CalendarUtils.dayForWeek(nextDate, "yyyy-MM-dd");
                            if(duplicateTypeValue.indexOf(weekDay.toString()) != -1&&weekDay.toString().equals(duplicateTypeValue.substring(duplicateTypeValue.length()-1, duplicateTypeValue.length()))){
                                endDate = CalendarUtils.addDays(nextDate, intervals, "yyyy-MM-dd");
                                Map<String, String> map = new HashMap<>();
                                map.put("startDate", nextDate);
                                map.put("endDate", endDate);
                                list.add(map);
                                i++;
                                break;
                            }else if(duplicateTypeValue.indexOf(weekDay.toString()) != -1){
                                endDate = CalendarUtils.addDays(nextDate, intervals, "yyyy-MM-dd");
                                Map<String, String> map = new HashMap<>();
                                map.put("startDate", nextDate);
                                map.put("endDate", endDate);
                                list.add(map);
                            }
                        }else if(flag == 1){
                            model = true;
                            break;
                        }
                    }
                    if(model) {
                        break;
                    }
                }
            }
        }else if("month".equals(duplicateType)){
            if("always".equals(duplicateEndType) || "endTime".equals(duplicateEndType)){
                if("endTime".equals(duplicateEndType)){
                    int result = CalendarUtils.compareDateStr(duplicateEndTypeValue, searchEndDate);
                    if(result == 2){
                        searchEndDate = duplicateEndTypeValue;
                    }
                }
                String repeatDate = CalendarUtils.setDay(startDate, duplicateTypeValue, "yyyy-MM-dd");
                int res=repeatDate.compareTo(startDate);
                if(res<0) {
                    repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",1);
                }
                while(true){
                    int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                    int flag1 = CalendarUtils.compareDateStr(repeatDate, startDate);
                    if(flag==0 || flag==2){
                        if(flag1 != 0){
                            endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                            Map<String, String> map = new HashMap<>();
                            map.put("startDate", repeatDate);
                            map.put("endDate", endDate);
                            list.add(map);
                        }
                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",1);
                    }else{
                        break;
                    }
                }
            }else{//重复次数
                int i = 1,num = Integer.parseInt(duplicateEndTypeValue);
                String repeatDate = CalendarUtils.setDay(startDate, duplicateTypeValue, "yyyy-MM-dd");
                while(i <= num){
                    int flag = CalendarUtils.compareDateStr(repeatDate, searchEndDate);
                    int flag1 = CalendarUtils.compareDateStr(repeatDate, startDate);
                    if((flag==0 || flag==2) && flag1!=0){
                        endDate = CalendarUtils.addDays(repeatDate, intervals, "yyyy-MM-dd");
                        Map<String, String> map = new HashMap<>();
                        map.put("startDate", repeatDate);
                        map.put("endDate", endDate);
                        list.add(map);
                        i++;
                        repeatDate = CalendarUtils.addMonthsLimit(repeatDate,"yyyy-MM-dd",1);
                    }else{
                        break;
                    }
                }
            }
        }

        return list;
    }



    /**
     * 根据分类删除日程
     * @param categoryId
     * @return
     */
    public int delCalendarByCate(String ownerId,String categoryId,String corpId,String token){
        //查出此日程分类下所有的日程id，删除对应的消息提醒
        List<String> calendarIds = calendarDao.findIdByCategoryId(categoryId);
        if(CollectionUtils.isNotEmpty(calendarIds)) {
            calendarSendMsgUtils.deleteMessage(calendarIds,corpId,token);
        }
        return this.calendarDao.deleteByCategory(ownerId, categoryId);
    }

    /**
     * 根据非主日程修改主日程
     * @param calendar
     * @return
     */
    public int updateMainCalendar(Calendar calendar){
        return this.calendarDao.updateMainCalendar(calendar.getTitle(), calendar.getCalendarCategory(),
                calendar.getContent(), calendar.getParticipant(), calendar.getAddress(), calendar.getExpiryReminder(),
                calendar.getExpiryReminderTime(), calendar.getAttachment(), calendar.getViewer(), calendar.getMaintainer(),
                calendar.getDegreeOfImportance(),calendar.getBelongCalendar());
    }

    /**
     * 根据主日程删除属于其的非主日程
     * @param calendarId
     * @return
     */
    public int deleteByBelong(String calendarId){
        return this.calendarDao.deleteByBelong(calendarId);
    }

    /**
     * 获取重复日程子日程所属的主日程
     * @param calendarId
     * @param start
     * @param end
     * @return
     */
    public List<Calendar> getCalendarByBelong(String calendarId,String start,String end){
        Date startDate = null,endDate = null;
        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");
        return this.calendarDao.findCalendarByBelong(calendarId, startDate, endDate);
    }

    /**
     * 删除当前及以后的重复日程
     * @param calendarId
     * @param start
     * @return
     */
    public int deleteAfter(String calendarId, Date start){
        return this.calendarDao.deleteAfter(calendarId, start);
    }

    /**
     * 获取共享给我的日程、日程分类所属人
     * @param userId
     * @param corpId
     * @return
     */
    public List<Map<String, String>> getShareOwner(String userId, String corpId, String token){

        //获取用户,组织,群组,岗位id;
        List<String> allIdList = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
        List<List<String>> allIdResultList = new ArrayList<List<String>>();
        int allIdCount = 1;
        if(allIdList.size()>200) {
            int size = allIdList.size();
            allIdCount = (size + 200 - 1) / 200;
            for(int i = 0; i < allIdCount; i++) {
                List<String> subList = allIdList.subList(i * 200, ((i + 1) * 200 > size ? size : 200 * (i + 1)));
                allIdResultList.add(subList);
            }
        }else {
            allIdResultList.add(allIdList);
        }
        //获取共享给我的可查看、可维护日程的拥有人
        StringBuffer sql = new StringBuffer();
        sql.append(" select a.calendar_owner from ( ");
        sql.append(" select o.calendar_owner from oa_calendar o ");
        sql.append(" left join oa_calendar_scope s on s.fieldDataValue=o.maintainer ");
        if(allIdCount>1) {
            sql.append("where (( s.scopeValue in ");
            for(int i=1;i<=allIdCount;i++) {
                sql.append(" (?"+i+")"+(i==allIdCount? ")" : "or s.scopeValue in "));
            }
            sql.append(" and s.fieldDataValue=o.maintainer ");
            sql.append(" and o.calendar_owner <> ?"+(allIdCount+1)+") ");
        }else {
            sql.append("where ( s.scopeValue in (?1) and s.fieldDataValue=o.maintainer ");
            sql.append(" and o.calendar_owner <> ?"+(allIdCount+1)+") ");
        }

        sql.append(" union ");
        sql.append(" select o.calendar_owner from oa_calendar o ");
        sql.append(" left join oa_calendar_scope s on s.fieldDataValue=o.viewer ");
        if(allIdCount>1) {
            sql.append(" where ( (s.scopeValue in ");
            for(int i=1;i<=allIdCount;i++) {
                sql.append(" (?"+i+")"+(i==allIdCount? ")" : " or s.scopeValue in "));
            }
            sql.append(" and s.fieldDataValue=o.viewer ");
            sql.append(" and o.calendar_owner <> ?"+(allIdCount+1)+") ");
        }else {
            sql.append(" where ( s.scopeValue in (?1) and s.fieldDataValue=o.viewer ");
            sql.append(" and o.calendar_owner <> ?"+(allIdCount+1)+") ");
        }
        sql.append(" ) a ");
        Query query = super.getEntityManager().createNativeQuery(sql.toString());
        for(int i=1;i<=allIdCount;i++) {
            query.setParameter(i, allIdResultList.get(i-1));
        }
        query.setParameter(allIdCount+1, userId);
        List<String> calendar  = query.getResultList();


        //查询日程分类的可查看,可维护,可新建范围有我的分类所属人
        List<String> category = this.calendarCategoryService.getShareCategoryOwner(userId,corpId,token);

        //去重
        List<Map<String, String>> list;
        String ownerId = "";
        if(calendar!=null && !calendar.isEmpty()){
            for(int i=0;i<calendar.size();i++){
                ownerId = calendar.get(i);
                for(int j=0;j<category.size();j++){
                    if(ownerId.equals(category.get(j))){
                        category.remove(j);
                        break;
                    }
                }
            }
        }
        //获取用户信息
        list = this.getUserInfo(calendar,corpId,token);
        list.addAll(this.getUserInfo(category,corpId,token));

        //获取可以新建的共享人id
        List<String> canCreateList = this.calendarCategoryService.getShareCategoryOwnerCanCreate(userId,corpId,token);
        if(CollectionUtils.isNotEmpty(canCreateList)){
            for(Map<String, String> userMap : list){
                String onwerId = userMap.get("userId");
                if(canCreateList.contains(onwerId)){
                    userMap.put("canCreate","1");
                }else{
                    userMap.put("canCreate","0");
                }
            }
        }else{
            for(Map<String, String> userMap : list){
                userMap.put("canCreate","0");
            }
        }


        return list;
    }

    /**
     * 获取用户下级员工的信息
     * @param userId
     * @param token
     * @return
     */
    public List<Map<String, String>> getSubStaff(String userId,  String token) {
        List<Map<String,String>> list = new ArrayList<>();
        try {
            //获取下属，不带兼职组织
            List<Map<String,Object>> subUserList = userApiService.getSubUserByUserId(userId,"","1",token);
            if (CollectionUtils.isNotEmpty(subUserList)) {
                for (Map map : subUserList) {
                    Map<String,String> userMap = new HashMap<>();
                    userMap.put("name",StringUtils.null2String(map.get("userName")) + "(" + this.findUserOrg(StringUtils.null2String(map.get("id"))) + ")");
                    userMap.put("userId",StringUtils.null2String(map.get("id")));
                    userMap.put("type","sub");
                    userMap.put("createdDate",StringUtils.null2String(map.get("createdDate")));
                    userMap.put("sortNo",StringUtils.null2String(map.get("sortNo")));
                    list.add(userMap);
                }

            }
        } catch (Exception e) {
            LOG.error("查询人员信息异常",e);
        }
        return list;
    }

    /**
     * 获取用户信息，姓名、头像等
     * @param list
     * @param corpId
     * @param token
     * @return
     */
    public List<Map<String, String>> getUserInfo(List<String> list, String corpId, String token){
        List<Map<String, String>> result = new ArrayList<>();
        Map<String,Object> scopeName ;
        for(int i=0;i<list.size();i++){
            Map<String, String> map = new HashMap<>();
            String userId = list.get(i);
            map.put("userId", userId);
            if("1".equals(userId)){
                map.put("name", "系统管理员");
                map.put("image", "static/fui/images/admin.png");
            }else{
                scopeName = this.userApiService.getUser(userId, corpId, "", token);
                if(scopeName == null) {
                    continue;
                }
                if(MapUtils.isNotEmpty(scopeName)){
                    map.put("name", scopeName.get("userName").toString() + "(" + this.findUserOrg(userId) + ")");
                    map.put("fileName", StringUtils.null2String(scopeName.get("imgId")));
                    map.put("image", "");
                    map.put("sex",StringUtils.null2String( scopeName.get("sex")));
                }
            }
            result.add(map);
        }
        return result;
    }


    /**
     * 同步任务日程
     * @param map
     */
    public void synchronizeCalnear(Map<String, Object> map,String token){
        String syncId = map.get("syncId").toString();
        Calendar calendar = this.calendarDao.findSyncCalendar(syncId);
        Date startDate ;
        String ownerId = map.get("ownerId").toString();
        String part = "";
        if(calendar != null){
            startDate = calendar.getStartDate();
            part = StringUtils.null2String(calendar.getParticipant());
        }else{
            calendar = new Calendar();
            calendar.setSyncId(syncId);
            calendar.setDuplicateEndType("always");
            calendar.setDuplicateType("no");
            calendar.setExpiryReminder("no");
            calendar.setIsMain("1");

            startDate = (Date) map.get("startDate");
            calendar.setStartDate(startDate);
            String cateType = map.get("type").toString();
            String corpId = map.get("corpId").toString();
            calendar.setCorpId(corpId);
            List<CalendarCategory> categorys = this.calendarCategoryDao.getCategoryBySource(cateType, ownerId, corpId);
            CalendarCategory category = null;
            if (CollectionUtils.isNotEmpty(categorys)) {
                category = categorys.get(0);
            }
            if(category != null){
                calendar.setCalendarCategory(category.getId());
            }else{
                category = new CalendarCategory();
                if("calendarConManager".equals(cateType)){
                    category.setBackColor("#f79646");
                }else{
                    category.setBackColor("#548dd4");
                }
                category.setCategory("calendarSys");
                category.setCorpId(corpId);
                Map<String, Object> detail = new HashMap<String,Object>();
                if("calendarConManager".equals(cateType)) {
                    detail.put("name", "会议");
                }else if("calendarRemarkManage".equals(cateType)) {
                    detail.put("name", "任务");
                }
                if(detail!=null && !detail.isEmpty()){
                    category.setName(detail.get("name").toString());
                    category.setSource(cateType);
                    category = this.calendarCategoryDao.save(category);
                }
                calendar.setCalendarCategory(category.getId());
            }
        }
        calendar.setCalendarOwner(ownerId);

        Date endDate = (Date) map.get("endDate");
        int flag = CalendarUtils.compareDate(startDate, endDate);
        calendar.setEndDate(endDate);
        if(flag == 0){
            calendar.setIsAllDay("1");
        }else{
            calendar.setIsAllDay("0");
            calendar.setEndTime(CalendarUtils.getSeconds("23:59:59"));
        }

        String jsonPart = StringUtils.null2String(map.get("participant"));
        if("".equals(part)){
            part = UuidUtils.UUID();
        }
        calendar.setParticipant(part);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, jsonPart, "oa_calendar", "participant");

        calendar.setContent(StringUtils.null2String(map.get("content")));
        calendar.setTitle(map.get("title").toString());
        calendar.setAttachment(StringUtils.null2String(map.get("attachment")));
        this.save(calendar);
    }

    public int deleteSyncCalnear(String syncId){
        return this.calendarDao.deleteSyncCalendar(syncId);
    }

    /**
     * 移动端列表视图
     * @param pageable
     * @param sharedId
     * @param category
     * @param userId
     * @param corpId
     * @param title
     * @param viewType
     * @param start
     * @param end
     * @param token
     * @return
     */
    public List<Map<String, String>> getOaCalendarAll(Pageable pageable, String sharedId, String category, String userId, String corpId, String title, String viewType, String start, String end, String token, String leaderOrSub){
        //获取当前用户的参与日程和拥有日程
        List<String> maintainFieldValue = new ArrayList<>();
        Date startDate = null,endDate = null;
        List<Map<String, String>> maps = new ArrayList<>();
        List<Map> calList ;
        Map<String,Object> mapValue = new HashMap<String,Object>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        Sort sort = pageable == null ? null : pageable.getSort();
        String orderBy = "";
        if(sort != null){
            orderBy = " order by ";
            for (Order order : sort) {
                orderBy += order.getProperty() + " " + order.getDirection().name();
            }
        }

        if("".equals(orderBy) || " order by ".equals(orderBy)){
            orderBy = "order by start_date,start_time";
        }
        StringBuffer sql = new StringBuffer();
        sql.append("select o.id,o.title,o.start_date,o.createdBy,o.end_date,o.calendar_owner,o.duplicate_type,o.duplicate_interval,o.week_month_duplicateType week_month,");
        sql.append("o.duplicate_end_type,o.duplicate_end_type_value,o.is_main,c.name as category,su.user_name,o.participant,");
        sql.append("o.maintainer caleMaintain,c.maintainer cateMaintain,o.belong_calendar,o.calendar_category,o.sync_id,c.back_color,o.start_time,o.end_time,o.is_all_day,o.degree_of_importance,o.is_complate from oa_calendar o ");
        sql.append("left join oa_calendar_category c on c.id=o.calendar_category left join sys_user su on o.calendar_owner=su.id ");
        sql.append("where (((fn_date_format(o.start_date,'yyyy-MM-dd') >= fn_date_format(:startDate,'yyyy-MM-dd') and fn_date_format(o.start_date,'yyyy-MM-dd') <= fn_date_format(:endDate,'yyyy-MM-dd')) or (fn_date_format(o.end_date,'yyyy-MM-dd') >= fn_date_format(:startDate,'yyyy-MM-dd') and fn_date_format(o.end_date,'yyyy-MM-dd') <= fn_date_format(:endDate,'yyyy-MM-dd'))) or o.duplicate_type != 'no') and o.corp_id=:corpId and o.title like :title ");
        mapValue.put("startDate", startDate);
        mapValue.put("endDate", endDate);
        mapValue.put("corpId", corpId);
        mapValue.put("title", "%"+title+"%");
        if("share".equals(viewType)){
            //共享日程
            List<String> shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);
            //共享分类
            List<String> shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);
            List<String> cates = new ArrayList<>();
            List<String> source = this.getSysSources(corpId);
            cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
            if(cates.isEmpty()){
                cates.add("");
            }
            if(!"".equals(category)){
                List<String> categories = Arrays.asList(category.split(","));
                sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) and o.calendar_category not in (:categories)  ");
                sql.append(orderBy);
                mapValue.put("sharedId", sharedId);
                mapValue.put("shareCalFieldValue", shareCalFieldValue);
                mapValue.put("cates", cates);
                mapValue.put("categories", categories);
            }else{
                sql.append("and o.sync_module is null ");
                sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates))  ").append(orderBy);
                mapValue.put("sharedId", sharedId);
                mapValue.put("shareCalFieldValue", shareCalFieldValue);
                mapValue.put("cates", cates);
                maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    List<String> categories = Arrays.asList(category.split(","));
                    if(categories.contains(cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    sql.append("and ((o.calendar_owner=:userId and o.calendar_category not in (:categories)) or o.participant in (:partFieldValue)) ").append(orderBy);
                    mapValue.put("userId", userId);
                    mapValue.put("categories", categories);
                    mapValue.put("partFieldValue", partFieldValue);
                }else{
                    if("partCalendar".equals(cate.getCode())){
                        sql.append("and o.participant in (:partFieldValue)  ").append(orderBy);
                        mapValue.put("partFieldValue", partFieldValue);
                    }else{
                        sql.append("and o.calendar_category=:category  ").append(orderBy);
                        mapValue.put("category", category);
                    }
                }
            }else{
                StringBuffer sb = new StringBuffer(sql);
                if("1".equals(leaderOrSub)) {
                    sql.append(" and (c.code not in ('singlePerson','calendarSysPerson') or c.code is null) and o.sync_module is null ");
                }
                //sb.append(" and o.sync_module is null ");
                sql.append(" and c.category != 'calendarSys' ");
                sb.append(" and c.category != 'calendarSys' ");
                String leaderSql = sb.toString();
                leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程' as category");
                sql.append("and (o.calendar_owner in (:userId)) ");
                sql.append(" union all ");
                sql.append(" " +leaderSql+" ");
                sql.append(" and (o.participant in (:partFieldValue)) order by start_time asc ");
                List<String> userIdList = Arrays.asList(userId.split(","));
                mapValue.put("userId", userIdList);
                mapValue.put("partFieldValue", partFieldValue);
            }
        }
        calList = super.findByListNativeQuery(sql.toString(), "",mapValue);

        List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
        CalendarCategory cate = null;
        if (CollectionUtils.isNotEmpty(cates)) {
            cate = cates.get(0);
        }
        if(calList!=null && !calList.isEmpty()){
            Map<String,String> textParams = new HashMap<String,String>();
            textParams.put("corpId", corpId);
            //----start----取出所有的calendarId,deletes,根据calendarId封装进Map中，key为calendarId，value为deletes
            List<String> calendarIds = new ArrayList<String>();
            for(int i=0;i<calList.size();i++){
                Map obj = calList.get(i);
                String calendarId = obj.get("id").toString();
                calendarIds.add(calendarId);
            }
            List<CalendarDelete> deleteCalendars = this.calendarDeleteDao.findByBelongs(calendarIds, endDate);
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            List<CalendarDelete> tempList = null;
            for (CalendarDelete calendarDelete : deleteCalendars) {
                if(deletesMap.get(calendarDelete.getBelongCalendar()) == null) {
                    tempList = new ArrayList<CalendarDelete>();
                    deletesMap.put(calendarDelete.getBelongCalendar(), tempList);
                }
                tempList.add(calendarDelete);
            }
            //----end----
            //---查询所有编辑过的重复日程的子日程，封装进map，key为主日程id，value为对应的编辑过的子日程集合---start
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> tempRepeats = null;
            List<Calendar> repeatCalendars = this.calendarDao.findCalendarByBelongs(calendarIds, DateUtils.parseDate(start, "yyyy-MM-dd"), DateUtils.parseDate(end, "yyyy-MM-dd"));
            for (Calendar calendar : repeatCalendars) {
                if(repeatsMap.get(calendar.getBelongCalendar()) == null) {
                    tempRepeats = new ArrayList<Calendar>();
                    repeatsMap.put(calendar.getBelongCalendar(), tempRepeats);
                }
                tempRepeats.add(calendar);
            }
            //---end----
            for(int i=0;i<calList.size();i++){
                String start_time="";String end_time="";
                Map obj =  calList.get(i);
                String calendarStart = CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy-MM-dd");
                String calendarEnd = (Date) obj.get("end_date")==null ? calendarStart : CalendarUtils.getStrByDate((Date) obj.get("end_date"), "yyyy-MM-dd");
                String calendarId = obj.get("id").toString();
                int sflag = CalendarUtils.compareDateStr(calendarStart, start);
                int eflag = CalendarUtils.compareDateStr(calendarStart, end);
                if(sflag!=2 && eflag!=1){
                    Map<String, String> map = new HashMap<>();
                    //查询当前用户是否已经完成该日程
                    String isComplate = StringUtils.equals("1", StringUtils.null2String(obj.get("is_complate")))?"1":"0";

                    List<String> partIdList = new ArrayList<>();
                    partIdList = calendarFinishedDao.findPartId(calendarId);
                    if("1".equals(leaderOrSub) || "share".equals(viewType)){//领导、下属日程下 如果日程拥有人完成就是日程完成了
                        if (partIdList.contains(obj.get("calendar_owner").toString())) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }else{//我的日程
                        // 当前用户是否在日程完成人员ID集合中
                        if (partIdList.contains(userId)) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }
                    map.put("isComplate",isComplate);

                    map.put("participant2",StringUtils.null2String(obj.get("participant")));

                    map.put("createdBy",StringUtils.null2String(obj.get("createdBy")));
                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                    String calendarMaintain = StringUtils.null2String(obj.get("caleMaintain"));
                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                    //维护权限
                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                        map.put("limitForMaintain","1");
                    }else {
                        map.put("limitForMaintain","0");
                    }
                    map.put("startDate", CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy年MM月dd日"));
                    start_time = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                    end_time = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                    map.put("start", calendarStart+" "+start_time);
                    map.put("end", calendarEnd+" "+end_time);
                    map.put("id", calendarId);
                    map.put("title", obj.get("title").toString());
                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                    }else {
                        map.put("degreeOfImportance", "1");
                    }
                    map.put("backColor", obj.get("back_color").toString());
                    map.put("syncId", StringUtils.null2String(obj.get("sync_id")==null?"":obj.get("sync_id").toString()));
                    map.put("isAllDay", obj.get("is_all_day").toString());
                    if("参与日程".equals(obj.get("category").toString()) && !"share".equals(viewType)){
                        map.put("category", "参与日程");
                        map.put("duplicate_type",StringUtils.null2String(obj.get("duplicate_type")));
                        if(StringUtils.isNotEmpty(StringUtils.null2String(obj.get("duplicate_type"))) && !StringUtils.equals(StringUtils.null2String(obj.get("duplicate_type")),"no")) {
                            if(StringUtils.equals("1",StringUtils.null2String(obj.get("is_main")))) {
                                map.put("repeat","0");
                            }else {
                                map.put("repeat","1");
                            }
                        }
                        map.put("categoryId", cate.getId());
                        map.put("isMaintain", "0");
                    }else{
                        map.put("category", obj.get("category").toString());
                        map.put("categoryId", obj.get("calendar_category").toString());
                        map.put("isMaintain", "1");
                    }
                    if("share".equals(viewType)){
                        if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(obj.get("caleMaintain")==null?"":obj.get("caleMaintain").toString())||maintainFieldValue.contains(obj.get("cateMaintain")==null?"":obj.get("cateMaintain").toString()))){
                            map.put("isMaintain", "1");
                            if("0".equals(obj.get("is_main").toString())){
                                Calendar main = this.calendarDao.findById(obj.get("belong_calendar").toString()).get();
                                CalendarCategory mainCate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                                if(maintainFieldValue.contains(StringUtils.null2String(main.getMaintainer()))
                                        ||maintainFieldValue.contains(StringUtils.null2String(mainCate.getMaintainer()))){
                                    map.put("showEditMsg", "1");
                                }
                            }
                        }else{
                            map.put("isMaintain", "0");
                        }
                    }
                    if("1".equals(obj.get("calendar_owner").toString())){
                        map.put("owner", "系统管理员");
                    }else{
                        textParams.put("id", obj.get("calendar_owner").toString());
                        textParams.put("thirdType", "");
						/*Map<String,Object> scopeName = this.userApiService.getUser(obj.get("calendar_owner").toString(), corpId, "", token);
						if(scopeName!=null && !scopeName.isEmpty()){
							map.put("owner", scopeName.get("userName").toString());
						}*/
                        map.put("owner", obj.get("user_name").toString());
                    }
                    map.put("belong", obj.get("belong_calendar")==null?calendarId:obj.get("belong_calendar").toString());
                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                    if("0".equals(obj.get("is_main").toString())){
                        map.put("repeat", "1");
                    }else if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString()) && !"参与日程".equals(map.get("category"))){
                        map.put("repeat", "0");
                    }
                    maps.add(map);
                }
                if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString())){
                    List<Map<String, String>> repeatList ;
                    String weekMonthDuplicateType = StringUtils.null2String(obj.get("week_month"));
                    repeatList = this.getDataMsg(obj.get("duplicate_type").toString(), StringUtils.null2String(obj.get("duplicate_interval")), obj.get("duplicate_end_type").toString(), obj.get("duplicate_end_type_value")==null?"":obj.get("duplicate_end_type_value").toString(), calendarStart, calendarEnd, end,weekMonthDuplicateType);
                    if(repeatList!=null && !repeatList.isEmpty()){
                        //List<CalendarDelete> deletes = new ArrayList<>();
                        //deletes = this.calendarDeleteDao.findByBelong(calendarId.toString(), endDate);
                        List<CalendarDelete> deletes = deletesMap.get(calendarId);
                        String delFlag = "",calStart = "";
                        for(int j=0;j<repeatList.size();j++){
                            Map<String, String> date = repeatList.get(j);
                            calStart = date.get("startDate");
                            int flag = 0;
                            if(deletes!=null && !deletes.isEmpty()){
                                for(int k=0;k<deletes.size();k++){
                                    CalendarDelete delete = deletes.get(k);
                                    if(delete != null){
                                        delFlag = delete.getDeleteType();
                                        if("current".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));

                                        }else if("after".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }
                                        if(flag == 0){
                                            break;
                                        }
                                    }
                                }
                                if(flag==0 && "current".equals(delFlag)){
                                    continue;
                                }else if(flag==0 && "after".equals(delFlag)){
                                    break;
                                }
                            }
                            int flag1 = CalendarUtils.compareDateStr(calStart, start);
                            int flag2 = CalendarUtils.compareDateStr(calStart, end);
                            if(flag1!=2 && flag2!=1){
                                //List<Calendar> repeats = new ArrayList<>();
                                //repeats = this.calendarDao.findCalendarByBelong(calendarId, startDate, endDate);
                                List<Calendar> repeats = repeatsMap.get(calendarId);
                                boolean equal = true;
                                if(repeats!=null && !repeats.isEmpty()){
                                    for(int k=0;k<repeats.size();k++){
                                        Calendar repeat = repeats.get(k);
                                        int flag3 = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                        if(flag3 == 0){
                                            equal = false;
                                            break;
                                        }
                                    }
                                }
                                if(equal){
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", calendarId);
                                    //查询当前用户是否已经完成该日程
                                    String isComplate = StringUtils.equals("1", StringUtils.null2String(obj.get("is_complate")))?"1":"0";
                                    String calendarDate = obj.get("start_date").toString();
                                    if(StringUtils.isNotEmpty(calendarDate)) {
                                        String day = date.get("startDate").toString();
                                        if(!StringUtils.equals(calendarDate, day)) {
                                            isComplate = "0";
                                        }
                                    }
                                    map.put("isComplate",isComplate);

                                    map.put("participant2",StringUtils.null2String(obj.get("participant")));

                                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                                    String calendarMaintain = StringUtils.null2String(obj.get("caleMaintain"));
                                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                                    //维护权限
                                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                                        map.put("limitForMaintain","1");
                                    }else {
                                        map.put("limitForMaintain","0");
                                    }
                                    Date d = new Date();

                                    d = CalendarUtils.getDataByStr(date.get("startDate"), "yyyy-MM-dd");

                                    map.put("startDate", CalendarUtils.getStrByDate(d, "yyyy年MM月dd日"));
                                    start_time = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                                    end_time = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                                    map.put("start", calStart+" "+start_time);
                                    map.put("end", date.get("endDate")+" "+end_time);
                                    map.put("belong", calendarId);
                                    map.put("title", obj.get("title").toString());
                                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                                    }else {
                                        map.put("degreeOfImportance", "1");
                                    }
                                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                                    map.put("backColor", obj.get("back_color").toString());
                                    map.put("isAllDay", obj.get("is_all_day").toString());
                                    map.put("syncId", StringUtils.null2String(obj.get("sync_id")==null?"":obj.get("sync_id").toString()));
                                    if("1".equals(obj.get("calendar_owner").toString())){
                                        map.put("owner", "系统管理员");
                                    }else{
                                        textParams.put("id", obj.get("calendar_owner").toString());
                                        textParams.put("thirdType", "");
										/*Map<String,Object> scopeName = this.userApiService.getUser(obj.get("calendar_owner").toString(), corpId, "", token);
										if(scopeName != null && !scopeName.isEmpty()){
											map.put("owner", scopeName.get("userName").toString());
										}*/
                                        map.put("owner", obj.get("user_name").toString());
                                    }
                                    if("参与日程".equals(obj.get("category").toString()) && !"share".equals(viewType)){
                                        map.put("category", "参与日程");
                                        map.put("repeat","1");
                                        map.put("categoryId", cate.getId());
                                        map.put("isMaintain", "0");
                                    }else{
                                        map.put("category",obj.get("category").toString());
                                        map.put("isMaintain", "1");
                                        map.put("categoryId", obj.get("calendar_category").toString());
                                        map.put("repeat", "1");
                                    }
                                    if("share".equals(viewType)){
                                        if(maintainFieldValue.contains(obj.get("caleMaintain")==null?"":obj.get("caleMaintain").toString())||maintainFieldValue.contains(obj.get("cateMaintain")==null?"":obj.get("cateMaintain").toString())){
                                            map.put("isMaintain", "1");
                                            map.put("showEditMsg", "1");
                                        }else{
                                            map.put("isMaintain", "0");
                                        }
                                    }
                                    maps.add(map);
                                }
                            }
                            if(flag2 == 1){
                                break;
                            }
                        }
                    }
                }
            }
        }
        return maps;
    }

    public int deleteByCarlendarId(String id) {
        return this.calendarDao.deleteByCarlendarId(id);
    }

    /**
     * 移动端列表视图
     * @param pageable
     * @param sharedId
     * @param category
     * @param userId
     * @param corpId
     * @param title
     * @param viewType
     * @param start
     * @param end
     * @param token
     * @param search
     * @param searchTime
     * @return
     * @throws ParseException
     */
    public List<Map<String, String>> getOaCalendarAllSearch(Pageable pageable, String sharedId, String category, String userId, String corpId, String title, String viewType, String start, String end, String token,String search,String searchTime,String leaderOrSub) throws ParseException{
        //获取当前用户的参与日程和拥有日程
        List<String> maintainFieldValue = new ArrayList<>();
        Date startDate = null,endDate = null;
        List<Map<String, String>> maps = new ArrayList<>();
        List<Map> calList ;
        Map<String,Object> mapValue = new HashMap<String,Object>();

        startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
        endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");

        Sort sort = pageable == null ? null : pageable.getSort();
        String orderBy = "";
        if(sort != null){
            orderBy = " order by ";
            for (Order order : sort) {
                orderBy += order.getProperty() + " " + order.getDirection().name();
            }
        }
        if("".equals(orderBy) || " order by ".equals(orderBy)){
            orderBy = "order by start_date";
        }
        StringBuffer sql = new StringBuffer();
        sql.append("select o.id,o.title,o.start_date,o.content,o.end_date,o.calendar_owner,o.duplicate_type,o.duplicate_interval,o.week_month_duplicateType week_month,");
        sql.append("o.duplicate_end_type,o.duplicate_end_type_value,o.is_main,c.name as category,o.participant,");
        sql.append("o.maintainer caleMaintain,c.maintainer cateMaintain,o.belong_calendar,o.calendar_category,o.sync_id,c.back_color,o.start_time,o.end_time,o.is_all_day,o.degree_of_importance,o.is_complate from oa_calendar o ");
        sql.append("left join oa_calendar_category c on c.id=o.calendar_category ");
        if(!searchTime.isEmpty()) {
            startDate = null;
            sql.append("where o.corp_id=:corpId and o.title like :title ");
            sql.append("and ((fn_date_format(o.start_date,'yyyy-MM-dd') like :searchTime ) or o.duplicate_type != 'no') ");
            mapValue.put("searchTime", "%"+searchTime+"%");
            mapValue.put("corpId", corpId);
            mapValue.put("title", "%"+title+"%");
        }else {
            sql.append("where (((fn_date_format(o.start_date,'yyyy-MM-dd') >= fn_date_format(:startDate,'yyyy-MM-dd') and fn_date_format(o.start_date,'yyyy-MM-dd') <= fn_date_format(:endDate,'yyyy-MM-dd')) or (fn_date_format(o.end_date,'yyyy-MM-dd') >= fn_date_format(:startDate,'yyyy-MM-dd') and fn_date_format(o.end_date,'yyyy-MM-dd') <= fn_date_format(:endDate,'yyyy-MM-dd'))) or o.duplicate_type != 'no') and o.corp_id=:corpId and o.title like :title ");
            mapValue.put("startDate", startDate);
            mapValue.put("endDate", endDate);
            mapValue.put("corpId", corpId);
            if(StringUtils.isNotEmpty(title)){
                title = title.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
            }
            mapValue.put("title", "%"+title+"%");
        }
        if(!search.isEmpty()) {
            if(StringUtils.isNotEmpty(search)){
                search = search.replace("_", "\\_").replace("%", "\\%").replace("'", "''");
            }
            sql.append("and o.title like :search " + SqlUtils.getSQLEscape(search));
            mapValue.put("search", "%"+search+"%");
        }
        if("share".equals(viewType)){
            //共享日程
            List<String> shareCalFieldValue = this.getFieldValue(userId,sharedId, "1",corpId,token);
            //共享分类
            List<String> shareCatFieldValue = this.getFieldValue(userId,sharedId, "2",corpId,token);
            List<String> cates = new ArrayList<>();
            List<String> source = this.getSysSources(corpId);
            cates = this.calendarCategoryDao.getSharedCategory(sharedId, shareCatFieldValue,source);
            if(cates.isEmpty()){
                cates.add("");
            }
            sql.append("and o.sync_module is null ");
            if(!"".equals(category)){
                List<String> categories = Arrays.asList(category.split(","));
                sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) and o.calendar_category not in (:categories) ");
                sql.append(orderBy);
                mapValue.put("sharedId", sharedId);
                mapValue.put("shareCalFieldValue", shareCalFieldValue);
                mapValue.put("cates", cates);
                mapValue.put("categories", categories);
            }else{
                sql.append("and o.calendar_owner=:sharedId and (o.viewer in (:shareCalFieldValue) or o.maintainer in (:shareCalFieldValue) or o.calendar_category in (:cates)) ").append(orderBy);
                mapValue.put("sharedId", sharedId);
                mapValue.put("shareCalFieldValue", shareCalFieldValue);
                mapValue.put("cates", cates);
                maintainFieldValue = this.getMaintainFieldValue(userId,sharedId,corpId,token);
            }
        }else{
            List<String> partFieldValue = this.getFieldValue(userId,"", "3",corpId,token);
            if(!"".equals(category)){
                List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
                CalendarCategory cate = null;
                if (CollectionUtils.isNotEmpty(cates)) {
                    cate = cates.get(0);
                }
                if(category.contains(",")){
                    List<String> categories = Arrays.asList(category.split(","));
                    if(categories.contains(cate.getId())){//包括参与日程
                        partFieldValue.clear();
                        partFieldValue.add("");
                    }
                    sql.append("and ((o.calendar_owner=:userId and o.calendar_category not in (:categories)) or o.participant in (:partFieldValue)) ").append(orderBy);
                    mapValue.put("userId", userId);
                    mapValue.put("categories", categories);
                    mapValue.put("partFieldValue", partFieldValue);
                }else{
                    if("partCalendar".equals(cate.getCode())){
                        sql.append("and o.participant in (:partFieldValue) ").append(orderBy);
                        mapValue.put("partFieldValue", partFieldValue);
                    }else{
                        sql.append("and o.calendar_category=:category ").append(orderBy);
                        mapValue.put("category", category);
                    }
                }
            }else{
                CalendarSetting oca = this.calendarSettingDao.getCalendarSettingValue("oaSysCalendarSet", corpId);
                if("1".equals(leaderOrSub)) {
                    sql.append(" and (c.code not in ('singlePerson','calendarSysPerson') or c.code is null) and o.sync_module is null ");
                }
                if("0".equals(oca.getSettingValue())){
                    sql.append("and c.category != 'calendarSys' ");
                    String leaderSql = sql.toString();
                    leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程' as category");
                    sql.append("and (o.calendar_owner in (:userId)) ");
                    sql.append(" union all ");
                    sql.append(" " +leaderSql+" ");
                    sql.append(" and (o.participant in (:partFieldValue)) order by start_time asc ");
                    List<String> userIdList = Arrays.asList(userId.split(","));
                    mapValue.put("userId", userIdList);
                    mapValue.put("partFieldValue", partFieldValue);
                }else{
                    CalendarSetting set = this.calendarSettingDao.getCalendarSettingValue("calendarSource", corpId);
                    String setting = StringUtils.null2String(set.getSettingValue());
                    if(!"".equals(setting)){
                        String[] sources = setting.split(",");
                        List<String> source = new ArrayList<>();
                        for (String str : sources) {
                            source.add(str);
                        }
                        sql.append("and (c.category = 'calendarOwner' or c.source in (:source)) ");
                        String leaderSql = sql.toString();
                        leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程' as category");
                        sql.append("and (o.calendar_owner in (:userId)) ");
                        sql.append(" union all ");
                        sql.append(" " +leaderSql+" ");
                        sql.append(" and (o.participant in (:partFieldValue)) order by start_time asc ");
                        List<String> userIdList = Arrays.asList(userId.split(","));
                        mapValue.put("userId", userIdList);
                        mapValue.put("partFieldValue", partFieldValue);
                        mapValue.put("source", source);

                    }else{
                        String leaderSql = sql.toString();
                        leaderSql = leaderSql.replaceAll("c.name as category", "'参与日程' as category");
                        sql.append("and (o.calendar_owner in (:userId)) ");
                        sql.append(" union all ");
                        sql.append(" " +leaderSql+" ");
                        sql.append(" and (o.participant in (:partFieldValue)) order by start_time asc ");
                        List<String> userIdList = Arrays.asList(userId.split(","));
                        mapValue.put("userId", userIdList);
                        mapValue.put("partFieldValue", partFieldValue);
                    }
                }
            }
        }
        calList = super.findByListNativeQuery(sql.toString(), "",mapValue);

        List<CalendarCategory> cates = this.calendarCategoryDao.getPartCategory(corpId);
        CalendarCategory cate = null;
        if (CollectionUtils.isNotEmpty(cates)) {
            cate = cates.get(0);
        }
        if(calList!=null && !calList.isEmpty()){
            Map<String,String> textParams = new HashMap<String,String>();
            textParams.put("corpId", corpId);
            for(int i=0;i<calList.size();i++){
                String start_time="";String end_time="";
                Map obj =  calList.get(i);
                String calendarStart = CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy-MM-dd");
                String calendarEnd = (Date) obj.get("end_date")==null ? calendarStart : CalendarUtils.getStrByDate((Date) obj.get("end_date"), "yyyy-MM-dd");
                String calendarId = obj.get("id").toString();
                int sflag = CalendarUtils.compareDateStr(calendarStart, start);
                int eflag = CalendarUtils.compareDateStr(calendarStart, end);
                if(sflag!=2 && eflag!=1){
                    Map<String, String> map = new HashMap<>();
                    map.put("startDate", CalendarUtils.getStrByDate((Date) obj.get("start_date"), "yyyy年MM月dd日"));
                    start_time = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                    end_time = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                    //查询当前用户是否已经完成该日程
                    String isComplate = "0";

                    List<String> partIdList = new ArrayList<>();
                    partIdList = calendarFinishedDao.findPartId(calendarId);
                    if("1".equals(leaderOrSub) || "share".equals(viewType)){//领导、下属日程下 如果日程拥有人完成就是日程完成了
                        if (partIdList.contains(obj.get("calendar_owner").toString())) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }else{//我的日程
                        // 当前用户是否在日程完成人员ID集合中
                        if (partIdList.contains(userId)) {
                            // 当前用户是完成日程状态
                            isComplate = "1";
                        }
                    }
                    map.put("isComplate",isComplate);
                    map.put("participant2",StringUtils.null2String(obj.get("participant")));
                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                    String calendarMaintain = StringUtils.null2String(obj.get("caleMaintain"));
                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                    //维护权限
                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                        map.put("limitForMaintain","1");
                    }else {
                        map.put("limitForMaintain","0");
                    }
                    map.put("start", calendarStart+" "+start_time);
                    map.put("end", calendarEnd+" "+end_time);
                    map.put("content",StringUtils.null2String(obj.get("content")));
                    map.put("id", calendarId);
                    map.put("title", obj.get("title").toString());
                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                    }else {
                        map.put("degreeOfImportance", "1");
                    }
                    map.put("backColor", obj.get("back_color").toString());
                    map.put("syncId", StringUtils.null2String(obj.get("sync_id")==null?"":obj.get("sync_id").toString()));
                    map.put("isAllDay",  obj.get("is_all_day").toString());
                    if("参与日程".equals(obj.get("category").toString()) && !"share".equals(viewType)){
                        map.put("category", "参与日程");
                        map.put("categoryId", cate.getId());
                        map.put("isMaintain", "0");
                        map.put("duplicate_type",StringUtils.null2String(obj.get("duplicate_type")));
                    }else{
                        map.put("category", obj.get("category").toString());
                        map.put("categoryId", obj.get("calendar_category").toString());
                        map.put("isMaintain", "1");
                    }
                    if("share".equals(viewType)){
                        if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(StringUtils.null2String(obj.get("caleMaintain")))||maintainFieldValue.contains(StringUtils.null2String(obj.get("cateMaintain"))))){
                            map.put("isMaintain", "1");
                            if("0".equals(obj.get("is_main").toString())){
                                Calendar main = this.calendarDao.findById(obj.get("belong_calendar").toString()).get();
                                CalendarCategory mainCate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                                if(maintainFieldValue.contains(StringUtils.null2String(main.getMaintainer()))
                                        ||maintainFieldValue.contains(StringUtils.null2String(mainCate.getMaintainer()))){
                                    map.put("showEditMsg", "1");
                                }
                            }
                        }else{
                            map.put("isMaintain", "0");
                        }
                    }
                    if("1".equals(obj.get("calendar_owner").toString())){
                        map.put("owner", "系统管理员");
                    }else{
                        textParams.put("id", obj.get("calendar_owner").toString());
                        textParams.put("thirdType", "");
                        Map<String,Object> scopeName = this.userApiService.getUser(obj.get("calendar_owner").toString(), corpId, "", token);
                        if(scopeName!=null&&!scopeName.isEmpty()){
                            map.put("owner", scopeName.get("userName").toString());
                        }
                    }
                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                    map.put("belong", obj.get("belong_calendar")==null?calendarId:obj.get("belong_calendar").toString());
                    if("0".equals(obj.get("is_main").toString())){
                        map.put("repeat", "1");
                    }else if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString()) && !"参与日程".equals(map.get("category"))){
                        map.put("repeat", "0");
                    }
                    maps.add(map);
                }
                if(!"no".equals(obj.get("duplicate_type").toString()) && "1".equals(obj.get("is_main").toString())){
                    List<Map<String, String>> repeatList = new ArrayList<>();
                    String weekMonthDuplicateType = StringUtils.null2String(obj.get("week_month"));
                    repeatList = this.getDataMsg(obj.get("duplicate_type").toString(), obj.get("duplicate_interval")==null?"":obj.get("duplicate_interval").toString(), obj.get("duplicate_end_type").toString(), obj.get("duplicate_end_type_value")==null?"":obj.get("duplicate_end_type_value").toString(), calendarStart, calendarEnd, end,weekMonthDuplicateType);
                    if(repeatList!=null && !repeatList.isEmpty()){
                        List<CalendarDelete> deletes ;
                        deletes = this.calendarDeleteDao.findByBelong(calendarId.toString(), endDate);
                        String delFlag = "",calStart = "";
                        for(int j=0;j<repeatList.size();j++){
                            Map<String, String> date = repeatList.get(j);
                            calStart = date.get("startDate");
                            int flag = 0;
                            if(deletes!=null && !deletes.isEmpty()){
                                for(int k=0;k<deletes.size();k++){
                                    CalendarDelete delete = deletes.get(k);
                                    if(delete != null){
                                        delFlag = delete.getDeleteType();
                                        if("current".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }else if("after".equals(delFlag)){
                                            flag = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                        }
                                        if(flag == 0){
                                            break;
                                        }
                                    }
                                }
                                if(flag==0 && "current".equals(delFlag)){
                                    continue;
                                }else if(flag==0 && "after".equals(delFlag)){
                                    break;
                                }
                            }
                            int flag1 = CalendarUtils.compareDateStr(calStart, start);
                            int flag2 = CalendarUtils.compareDateStr(calStart, end);
                            if(flag1!=2 && flag2!=1){
                                List<Calendar> repeats ;
                                repeats = this.calendarDao.findCalendarByBelong(calendarId);
                                boolean equal = true;
                                if(repeats!=null && !repeats.isEmpty()){
                                    for(int k=0;k<repeats.size();k++){
                                        Calendar repeat = repeats.get(k);
                                        int flag3 = CalendarUtils.compareDateStr(calStart, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                        if(flag3 == 0){
                                            equal = false;
                                            break;
                                        }
                                    }
                                }
                                if(equal){
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", calendarId);
                                    Date d = new Date();

                                    d = CalendarUtils.getDataByStr(date.get("startDate"), "yyyy-MM-dd");

                                    map.put("startDate", CalendarUtils.getStrByDate(d, "yyyy年MM月dd日"));
                                    start_time = CalendarUtils.getTime(Integer.parseInt(obj.get("start_time").toString()));
                                    end_time = CalendarUtils.getTime(Integer.parseInt(obj.get("end_time").toString()));
                                    String isComplate = "0";
                                    String calendarDate = obj.get("start_date").toString();
                                    if(StringUtils.isNotEmpty(calendarDate)) {
                                        String day = date.get("startDate").toString();
                                        if(!StringUtils.equals(calendarDate, day)) {
                                            isComplate = "0";
                                        }
                                    }

                                    //查询当前用户是否已经完成该日程

//                                    List<String> partIdList = new ArrayList<>();
//                                    partIdList = calendarFinishedDao.findPartId(calendarId);
//                                    if("1".equals(leaderOrSub)){//领导、下属日程下 如果日程拥有人完成就是日程完成了
//                                        if (partIdList.contains(obj.get("calendar_owner").toString())) {
//                                            // 当前用户是完成日程状态
//                                            isComplate = "1";
//                                        }
//                                    }else{//我的日程
//                                        // 当前用户是否在日程完成人员ID集合中
//                                        if (partIdList.contains(userId)) {
//                                            // 当前用户是完成日程状态
//                                            isComplate = "1";
//                                        }
//                                    }

                                    map.put("isComplate",isComplate);
                                    map.put("participant2",StringUtils.null2String(obj.get("participant")));
                                    //查询当前日程的的维护权限,日程所在分类的维护权限,当前日程是否是当前用户所创建
                                    map.put("createdByMine",StringUtils.equals(StringUtils.null2String(obj.get("createdBy")),userId)?"1":"0");
                                    String calendarMaintain = StringUtils.null2String(obj.get("caleMaintain"));
                                    String cateMaintain = StringUtils.null2String(obj.get("cateMaintain"));
                                    String scopeCalendarMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar", "maintainer",calendarMaintain);
                                    String scopeCategoryMain = popUserScopeUtilService.getScopeTypeValue( "oa_calendar_scope", "oa_calendar_category", "maintainer",cateMaintain);
                                    //维护权限
                                    if(scopeCalendarMain.contains(userId) || scopeCategoryMain.contains(userId)) {
                                        map.put("limitForMaintain","1");
                                    }else {
                                        map.put("limitForMaintain","0");
                                    }
                                    map.put("start", calStart+" "+start_time);
                                    map.put("end", date.get("endDate")+" "+end_time);
                                    map.put("belong", calendarId);
                                    map.put("title", obj.get("title").toString());
                                    if(obj.get("degree_of_importance")!=null && obj.get("degree_of_importance")!="") {
                                        map.put("degreeOfImportance", obj.get("degree_of_importance").toString());
                                    }else {
                                        map.put("degreeOfImportance", "1");
                                    }
                                    map.put("backColor", obj.get("back_color").toString());
                                    map.put("isAllDay",  obj.get("is_all_day").toString());
                                    map.put("calendarOwner", StringUtils.null2String(obj.get("calendar_owner")));
                                    map.put("syncId", StringUtils.null2String(obj.get("sync_id")==null?"":obj.get("sync_id").toString()));
                                    if("1".equals(obj.get("calendar_owner").toString())){
                                        map.put("owner", "系统管理员");
                                    }else{
                                        textParams.put("id", obj.get("calendar_owner").toString());
                                        textParams.put("thirdType", "");
                                        Map<String,Object> scopeName = this.userApiService.getUser(obj.get("calendar_owner").toString(), corpId, "", token);
                                        if(scopeName!=null&&!scopeName.isEmpty()){
                                            map.put("owner", scopeName.get("userName").toString());
                                        }
                                    }
                                    if(!userId.equals(obj.get("calendar_owner").toString()) && !"share".equals(viewType)){
                                        map.put("category", "参与日程");
                                        map.put("repeat","1");
                                        map.put("categoryId", cate.getId());
                                        map.put("isMaintain", "0");
                                    }else{
                                        map.put("category", obj.get("category").toString());
                                        map.put("isMaintain", "1");
                                        map.put("categoryId", obj.get("category").toString());
                                        map.put("repeat", "1");
                                    }
                                    if("share".equals(viewType)){
                                        if(maintainFieldValue.contains(obj.get("caleMaintain")==null?"":obj.get("caleMaintain").toString())||maintainFieldValue.contains(obj.get("cateMaintain")==null?"":obj.get("cateMaintain").toString())){
                                            map.put("isMaintain", "1");
                                            map.put("showEditMsg", "1");
                                        }else{
                                            map.put("isMaintain", "0");
                                        }
                                    }
                                    maps.add(map);
                                }
                            }
                            if(flag2 == 1){
                                break;
                            }
                        }
                    }
                }
            }
        }
        return maps;
    }

    public List<Calendar> getCalendarBySetting(String[] reminds) {
        return calendarDao.getCalendarBySetting(reminds);
    }


    /**
     * 发送钉钉推送
     */
    public void sendMsgToApp(String corpId, String module, String msgtype, Map<String, Object> ds,
                             HttpServletRequest request, String token) {
        try {
            // 发送信息
            String message = "";
            String messageUrl = "";
            String context = "";
            // 链接ip
            String webUrl = "";
            long appId = 0L;
            String corpReally = "";
            String dingdingType = GlobalConstant.getConfig("dingding.type");
            if ("corp".equals(dingdingType)) { // 企业dingding.module.document.agentId
                Map am = mobileAppInfoService.getMobileAppInfoByAppCode("0", MODULETYPE, corpId, token);
                if(am != null && am.get("agentId") != null) {
                    appId = Long.parseLong(am.get("agentId").toString());
                }
                corpReally = GlobalConstant.getConfig("dingding.corpId");
            } else {
                String appIdString = GlobalConstant.getConfig(
                        (new StringBuilder()).append("dingisv.module.").append(module).append(".appid").toString());
                if (appIdString != null && !"".equals(appIdString)) {
                    appId = Long.parseLong(appIdString);
                }
                corpReally = corpId;
            }
            webUrl = GlobalConstant.getFlexOfficePath(request);
            context = convertContextPath(webUrl);
            if(StringUtils.isNotEmpty(context) && context.length()>=1){
                context = "&contextPath="+context;
            }else{
                context = "";
            }
            try {
                messageUrl = webUrl + "/mobile/dist/index.html" + "?appid=" + appId + context
                        + "&corpid=" + corpReally + "&dd_nav_bgcolor=FF5E97F6";
                if("".equals(ds.get("endTime"))) {
                    message = "{\"message_url\":\"" + messageUrl + "\","
                            + "\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"日程提醒\"}," + "\"body\": {\"title\":\""
                            +""+ds.get("title")+"\"," + "\"form\": [{\"key\": \"日程分类:\",\"value\": \""+ds.get("calendarCategory")+"\"},{\"key\": \"日程日期:\",\"value\": \""+ds.get("startTime")+"\"}]" + "}}";
                }else {
                    message = "{\"message_url\":\"" + messageUrl + "\","
                            + "\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"日程提醒\"}," + "\"body\": {\"title\":\""
                            +""+ds.get("title")+"\"," + "\"form\": [{\"key\": \"日程分类:\",\"value\": \""+ds.get("calendarCategory")+"\"},{\"key\": \"开始时间:\",\"value\": \""+ds.get("startTime") + "\"},{\"key\": \"结束时间:\",\"value\": \""+ds.get("endTime")+"\"}]" + "}}";
                }
                Map<String,Object> messageMap = new HashMap<String, Object>();
                messageMap.put("oa", JsonUtils.readValue(message));
            } catch (Exception e) {
                LOG.error("json转换异常",e);
            }
        } catch (Exception e) {
            LOG.error("消息发送异常",e);
        }
    }

    public static String convertContextPath(String serverUrl){
        String context = "";
        serverUrl = serverUrl.substring(serverUrl.lastIndexOf("//")+2,serverUrl.length());
        int index = serverUrl.lastIndexOf("/");
        if(index>0){
            if(index == serverUrl.length()-1){// /在结尾
                context="";
            }else{
                context = serverUrl.substring(serverUrl.lastIndexOf("/")+1);
            }
        }else{
            context="";
        }
        return context;
    }

    /**
     * 导出日程方法
     * @param paramMaps
     * @return
     */
    public List<Calendar> getDemoExport(Map<String, String> paramMaps){
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        WebUser user = WebUtils.getCurrentUser();
        String userId = paramMaps.get("userId");
        String cateId = paramMaps.get("cateId");
        String startTime = paramMaps.get("startTime");
        String endTime =  paramMaps.get("endTime");
        String viewType = paramMaps.get("viewType");
        String leaderOrSub = paramMaps.get("leaderOrSub");
        String calendarCate = paramMaps.get("calendarCate");
        String leaderOrSubName = paramMaps.get("leaderOrSubName");
        String selectViewType = paramMaps.get("selectViewType");
        String customId = paramMaps.get("customId");

        //对领导人做处理
        List<String> userList = new ArrayList<>();
        List<Map<String,Object>> userMapList = new ArrayList<>();
        Map<String,Map<String,Object>> userIdForKeyMap = new HashMap<>();
        if(StringUtils.isNotBlank(userId)){
            userList = Arrays.asList(userId.split(","));
            userMapList = userApiService.getUserList(userId, user.getCorpId(), "", user.getJwtToken());

            if(CollectionUtils.isNotEmpty(userMapList)){
                for(Map<String,Object> userMap : userMapList){
                    userIdForKeyMap.put(userMap.get("id").toString(),userMap);
                }
            }
        }


        //开始结束时间查询
        if (StringUtils.isBlank(startTime)) {
            java.util.Calendar c = java.util.Calendar.getInstance();
            c.add(java.util.Calendar.YEAR,-5);
            startTime = sd.format(c.getTime());
        }
        if (StringUtils.isBlank(endTime)) {  //5年的日程
            java.util.Calendar c = java.util.Calendar.getInstance();
            c.add(java.util.Calendar.YEAR,5);
            endTime = sd.format(c.getTime());
        }
        List<Calendar> returnList = new ArrayList<>();
        try {
            returnList = new ArrayList<>();
            String result = "";
            if(StringUtils.equals(viewType, "calendar")) {
                result = getOaCalendar("", user.getUserId(), user.getCorpId(), "", cateId,"calendar", startTime, endTime, user.getJwtToken(),"",user);
            }else {
                if(StringUtils.equals(leaderOrSub, "leader")) {
                    result = getOaCalendar("", userId, user.getCorpId(), "", cateId,"calendar", startTime, endTime, user.getJwtToken(), "1",user);
                }else if(StringUtils.equals(leaderOrSub, "sub")) {
                    result = getOaCalendar("", userId, user.getCorpId(), "", cateId,"calendar", startTime, endTime, user.getJwtToken(), "1",user);
                }else {
                    result = getOaCalendar(userId, user.getUserId(), user.getCorpId(), "", cateId,"share", startTime, endTime, user.getJwtToken(), "",user);
                }
            }
            List<Map<String,String>> list = (List<Map<String,String>>) JSONArray.parse(result);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (CollectionUtils.isNotEmpty(list)) {
                Collections.sort(list, new Comparator<Map<String, String>>() {
                    @Override
                    public int compare(Map<String, String> o1, Map<String, String> o2) {
                        Date date1 = null;
                        Date date2 = null;
                        try {
                            date1 = format.parse(StringUtils.equals(StringUtils.null2String(o1.get("allDay")), "true")?o1.get("start")+" 00:00":o1.get("start").replace("T", " "));
                            date2 = format.parse(StringUtils.equals(StringUtils.null2String(o2.get("allDay")), "true")?o2.get("start")+" 00:00":o2.get("start").replace("T", " "));
                        }catch (ParseException e) {
                            LOG.error("时间转换异常",e);
                        }
                        return date2.compareTo(date1);
                    }
                });
                //取出所有日程的id
                List<String> ids = list.stream().map(map1->{
                    return StringUtils.null2String(map1.get("mainId"));
                }).collect(Collectors.toList());

                for(Map<String,String> resultMap : list){
                    //日程主键
                    String id = resultMap.get("mainId");
                    Date date ;
                    if (StringUtils.isNotBlank(StringUtils.null2String(resultMap.get("allDay")))) {
                        date = sd.parse(StringUtils.null2String(resultMap.get("start")));
                    }else{
                        date = s.parse(StringUtils.null2String(resultMap.get("start")).replace("T"," "));
                    }
                    //日程开始时间   小于查询开始时间   大于查询结束时间
                    if (date.getTime() < sd.parse(startTime).getTime() || date.getTime() > sd.parse(endTime).getTime()) {
                        continue;
                    }
                    StringBuffer sql = new StringBuffer();
                    sql.append(" select c.id,c.title,c.is_all_day,c.content,c.start_date,c.end_date, " +
                            " c.start_time,c.end_time,c.participant,c.expiry_reminder,c.expiry_reminder_time, " +
                            " c.duplicate_type,c.duplicate_interval,su1.user_name cowner,su2.user_name creater,cc.name cate_name, c.week_month_duplicateType as monthDuplicateType " +
                            " from oa_calendar c " +
                            " left join oa_calendar_category cc on cc.id = c.calendar_category " +
                            " left join sys_user su1 on su1.id = c.calendar_owner " +
                            " left join sys_user su2 on su2.id = c.createdBy " +
                            " where c.id = :id ");


                    Map<String,Object>  paramMap = new HashMap<>();
                    //日程分类查询
                    if (StringUtils.isNotBlank(cateId) && !StringUtils.equals(cateId, "402887f25fc451dd015fc47cb2ac0040")) {
                        sql.append(" and c.calendar_category = :cateId ");
                        paramMap.put("cateId",cateId);
                    }
                    paramMap.put("id",id);
                    List<Map> calendarList = super.findByListNativeQuery(sql.toString()," order by c.start_date desc",paramMap);
                    if (CollectionUtils.isNotEmpty(calendarList)) {
                        Calendar calendar ;
                        java.util.Calendar cal;
                        //根据参与人字段查找scope
                        String partScope ;
                        //参与人名称
                        String name ;
                        String duplicateType;
                        for (Map<String, Object> calMap : calendarList) {
                            calendar = new Calendar();
                            calendar.setExpiryReminder(StringUtils.null2String(calMap.get("expiry_reminder")));
                            calendar.setExpiryReminderTime(StringUtils.null2String(calMap.get("expiry_reminder_time")));
                            calendar.setIsAllDay(StringUtils.null2String(calMap.get("is_all_day")));
                            //全天日程判断   是否对结束日程赋值
                            if (StringUtils.equals("0", StringUtils.null2String(calMap.get("is_all_day")))) {//0不是全天  结束时间赋值
                                date = s.parse(StringUtils.null2String(resultMap.get("end")).replace("T"," "));
                                cal = java.util.Calendar.getInstance();
                                cal.setTime(date);
                                calendar.setEndTimeStr(s.format(cal.getTime()));
                                //开始时间
                                date = s.parse(StringUtils.null2String(resultMap.get("start")).replace("T"," "));
                                cal = java.util.Calendar.getInstance();
                                cal.setTime(date);
                                calendar.setStartTimeStr(s.format(cal.getTime()));
                            }else{
                                //开始时间
                                date = s.parse(StringUtils.null2String(resultMap.get("start")) + " 09:00");
                                cal = java.util.Calendar.getInstance();
                                cal.setTime(date);
                                calendar.setStartTimeStr(s.format(cal.getTime()));
                                //结束时间
                                date = s.parse(StringUtils.null2String(resultMap.get("start")) + " 18:00");
                                cal = java.util.Calendar.getInstance();
                                cal.setTime(date);
                                calendar.setEndTimeStr(s.format(cal.getTime()));
                            }
                            calendar.setId(StringUtils.null2String(calMap.get("id")));
                            calendar.setTitle(StringUtils.null2String(calMap.get("title")));
                            calendar.setContent(StringUtils.null2String(calMap.get("content")));
                            //拥有者和创建者
                            calendar.setCreaterName(StringUtils.null2String(calMap.get("creater")));
                            calendar.setCalendarOwnerName(StringUtils.null2String(calMap.get("cowner")));
                            if(StringUtils.equals(cateId, "402887f25fc451dd015fc47cb2ac0040")) {
                                calendar.setCateName("参与日程");
                                //songwy 要求改成显示本身的分类名
//                                calendar.setCateName(StringUtils.null2String(calMap.get("cate_name")));
                            }else {
                                calendar.setCateName(resultMap.get("classfiyName"));
                            }
                            duplicateType = StringUtils.null2String(calMap.get("duplicate_type"));
                            //重复类型
                            if("month".equals(duplicateType)){
                                calendar.setDupTypeName(getDupTypeName(StringUtils.null2String(calMap.get("duplicate_type")),
                                        StringUtils.null2String(calMap.get("monthDuplicateType"))));
                            }else{
                                calendar.setDupTypeName(getDupTypeName(StringUtils.null2String(calMap.get("duplicate_type")),
                                        StringUtils.null2String(calMap.get("duplicate_interval"))));
                            }
                            partScope = this.popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "participant", StringUtils.null2String(calMap.get("participant")));
                            name = userApiService.getScopeName(partScope,user.getCorpId(),user.getJwtToken());
                            calendar.setParticipantNames(name);
                            if("参与日程".equals(calendar.getCateName()) && !"myCalendar".equals(selectViewType) && !"shareCalendar".equals(selectViewType)){
                                String participant = StringUtils.null2String(calMap.get("participant"));
                                if(StringUtils.isNotBlank(participant)){
                                    List<String> scopeValueList = calendarDao.selectScopeValueList(participant);
                                    for(String partUserId : userList){
                                        if(scopeValueList.contains(partUserId)){
                                            calendar.setCalendarOwnerName(userIdForKeyMap.get(partUserId).get("userName").toString());
                                            returnList.add(calendar);
                                        }
                                    }
                                }
                            }else{
                                returnList.add(calendar);
                            }
                        };
                    }
                }
                if(StringUtils.equals(viewType, "calendar")) {

                    boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:mycalendar:05", user.getJwtToken());
                    if(logSet) {
                        if(StringUtils.isNoneEmpty(calendarCate) && !"请选择".equals(calendarCate)) {
                            this.logService.saveModuleLog("calendar:mycalendar:05", calendarCate,"");
                        }else {
                            this.logService.saveModuleLog("calendar:mycalendar:05", "全部日程","");
                        }
                    }

                }else if(StringUtils.equals(leaderOrSub, "leader")){
                    boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:leader:05", user.getJwtToken());
                    if(logSet) {
                        this.logService.saveModuleLog("calendar:leader:05", StringUtils.isNotEmpty(leaderOrSubName) ? leaderOrSubName : "全部领导日程","");
                    }
                }else if(StringUtils.equals(leaderOrSub, "sub")) {
                    if(StringUtils.equals(selectViewType, "customCalendar")){
                        boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:customCalendar:05", user.getJwtToken());
                        if(logSet) {
                            //获取自定义栏目信息
                            CalendarCustom calendarCustom = calendarCustomService.findOne(customId);
                            this.logService.saveModuleLog("calendar:customCalendar:05", calendarCustom != null && calendarCustom.getCustomName()!=null ? calendarCustom.getCustomName() : "","");
                        }
                    }else{
                        boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:sub:05", user.getJwtToken());
                        if(logSet) {
                            this.logService.saveModuleLog("calendar:sub:05", StringUtils.isNotEmpty(leaderOrSubName) ? leaderOrSubName : "下属日程","");
                        }
                    }
                }else {
                    boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:shareMe:05", user.getJwtToken());
                    if(logSet) {
                        this.logService.saveModuleLog("calendar:shareMe:05", "共享给我的日程","");
                    }
                }
            }

        } catch (ParseException e) {
            LOG.error("日程导出报错",e);
        }
        return returnList;
    }

    public static String toUtf8String(String s) throws UnsupportedEncodingException  {
        return new String(s.getBytes("GB2312"), "iso8859-1");
    }

    /**
     * 重复类型判断
     * @param type
     * @param interval
     * @return
     */
    private String getDupTypeName(String type, String interval) {
        String[] week = {"周一","周二","周三","周四","周五","周六","周日"};
        switch (Calendar.DuplicateTypeEnum.getByValue(type)) {
            case NO : return Calendar.DuplicateTypeEnum.NO.getValue();
            case DAY : return Calendar.DuplicateTypeEnum.DAY.getValue() + "(每隔" + interval + "天重复一次)";
            case WEEK :
                String[] arr = interval.split("");
                String text = Calendar.DuplicateTypeEnum.WEEK.getValue() + "每";
                for(int i = 0;i < arr.length ; i ++){
                    text += week[Integer.parseInt(arr[i])-1];
                    if(i != arr.length-1){
                        text += "、";
                    }
                }
                text += "重复";
                return text;
            case MONTH: return Calendar.DuplicateTypeEnum.MONTH.getValue() + "每月" + interval.substring(1,interval.length()).split("month")[0] + "重复";
            case YEAR:
                return  Calendar.DuplicateTypeEnum.YEAR.getValue() + "每年"+interval.substring(0,interval.length()-2) + "月"
                        + interval.substring(interval.length()-2,interval.length()) + "日重复";
            default:return "数据错误";
        }
    }

    /**
     * 给定时任务查询所有的日程
     * @param userId
     * @param corpId
     * @param token
     * @return
     */
    public List<Calendar> getCalendarList(String userId,String corpId,String startPush,String nextDate,String token) {
        //开始结束时间查询
        List<Calendar> returnList = new ArrayList<>();
        try {
            returnList = new ArrayList<>();
            String result = getOaCalendarTem("", userId, corpId, "",
                    "","calendar", startPush, nextDate, token, "remind");
            List<Map<String,String>> list = (List<Map<String,String>>) JSONArray.parse(result);
            if (CollectionUtils.isNotEmpty(list)) {
                Calendar calendar = null;
                String allDay ;
                for (Map<String, String> map : list) {
                    calendar = this.findOne(StringUtils.null2String(map.get("mainId")));
                    LOG.error("定时任务报错点",StringUtils.null2String(map.get("mainId")));
                    if (calendar != null) {
                        //将实体类从持久态改成游离态
                        super.detach(calendar);
                        allDay = StringUtils.null2String(map.get("allDay"));
                        if (StringUtils.isNotBlank(allDay) && Boolean.parseBoolean(allDay)) {
                            calendar.setStartDate(DateUtils.parseDate(StringUtils.null2String(map.get("start"))));
                        } else {
                            String start = StringUtils.null2String(map.get("start")).split("T")[0];
                            calendar.setStartDate(DateUtils.parseDate(start));
                            String end = StringUtils.null2String(map.get("end")).split("T")[0];
                            calendar.setEndDate(DateUtils.parseDate(end));
                        }
                        returnList.add(calendar);
                    }
                }
            }
        } catch (ParseException e) {
            LOG.error("转换异常",e);
        }
        return returnList;
    }

    /**
     * 获取后台设置参数
     * @param corpId
     * @param token
     * return (wxWork,ding,evoPortal)
     */
    public String getSysImType(String corpId, String token) {
        RestClient restClient = new RestClient(true);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("corpId", corpId);
        paramMap.put("mark", "sysImType");
        String type = configService.getConfigCache("sysImType", corpId,  token);
        if(type != null){
            return type;
        }
        return "";
    }

    /**
     * 获取后台设置参数
     * @param corpId
     * @param token
     * return (1:内部邮件,2：外部邮件,0：禁用)
     */
    public String getSysMailSetting(String corpId, String token) {
        RestClient restClient = new RestClient(true);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("corpId", corpId);
        paramMap.put("mark", "sysMailSetting");
        String type = configService.getConfigCache("sysImType", corpId,  token);
        if(type != null){
            return type;
        }
        return "";
    }

    /**
     * 获取后台设置参数
     * @param corpId
     * @param token
     * return (1:启用,0：禁用)
     */
    public String getSysSmsSetting(String corpId, String token) {
        RestClient restClient = new RestClient(true);
        String type = configService.getConfigCache("sysImType", corpId,  token);
        if(type != null){
            return type;
        }
        return "";
    }

    public List<Calendar> getCalendarPushAll(Date date, Date date2,Boolean isDuplicated) {
        if (isDuplicated) {
            return calendarDao.getCalendarPushAllWithDup(date2);
        }else {
            return calendarDao.getCalendarPushAll(date,date2);
        }
    }

    public List<Map<String, String>> getLeadListToString(List<Map<String, String>> result, Date dateStart) {
        for (Map<String, String> map : result) {
            String start = map.get("startWeek").toString();
            Integer weekDay = CalendarUtils.dayForWeek(start, "yyyy-MM-dd");
            String weekName = "";
            if(weekDay == 1) {
                weekName = "周一";
            }else if(weekDay == 2) {
                weekName = "周二";
            }else if(weekDay == 3) {
                weekName = "周三";
            }else if(weekDay == 4) {
                weekName = "周四";
            }else if(weekDay == 5) {
                weekName = "周五";
            }else if(weekDay == 6) {
                weekName = "周六";
            }else if(weekDay == 7) {
                weekName = "周日";
            }
            map.put("weekName", weekName);
            map.put("dayStart", start.substring(5,10).replace("-", "."));
            if( StringUtils.equals(map.get("isAllDay"), "1")) {
                map.put("start", start.substring(5,10));
                map.put("end", start.substring(5,10));
            }else {
                map.put("start", start.substring(5,16));
                map.put("end", map.get("endWeek").toString().substring(5,16));
            }
            ;
            map.put("color", "border-top: 2px solid "+ map.get("color").toString()+";");
        }
        return result;
    }

    //可查到被删除但保留在历史记录中的用户
    public List<Map> findUserName(String id){
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT user_name , is_delete from sys_user where id = :id  ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id",  id);
        List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
        if(list.size() == 0) {
            return null;
        }else {
            return list;
        }
    }

    //获取当前用户(所在组织-上级组织)名称
    public String findUserOrg(String userId){
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT su.user_name,su.org_id,so1.org_name nowOrgName,so2.org_name leaderOrgName from  ");
        sql.append(" sys_user su LEFT JOIN sys_org so1 ON su.org_id = so1.id LEFT JOIN sys_org so2 ON so1.parent_id =  so2.id ");
        sql.append(" WHERE su.id = :id ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id",  userId);
        List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
        if(CollectionUtils.isNotEmpty(list)) {
            Map map = list.get(0);
            return StringUtils.null2String(map.get("leaderOrgName")) + (StringUtils.isNotEmpty(StringUtils.null2String(map.get("leaderOrgName")))?"/":"") + StringUtils.null2String(map.get("nowOrgName"));
        }else {
            return null;
        }
    }

    //list<Map>根据时间字段排序
    public List<Map<String,String>> compareByStartTime(List<Map<String,String>> list ){
        List<Map<String,String>> ReturnList = new ArrayList();
        List<Map<String,String>> compareList = new ArrayList();
        for(Map map : list) {
            if(StringUtils.equals(map.get("isAllDay").toString(), "1")) {
                ReturnList.add(map);
            }else {
                compareList.add(map);
            }
        }
        if(CollectionUtils.isNotEmpty(compareList)) {
            Collections.sort(compareList, new Comparator<Map<String,String>>() {
                @Override
                public int compare(Map<String,String>  o1, Map<String,String> o2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date date1 = null;
                    Date date2 = null;
                    try {
                        date1 = format.parse(o1.get("start"));
                        date2 = format.parse(o2.get("start"));
                    }catch (ParseException e) {
                        LOG.error("时间转换异常",e);
                    }
                    return date1.compareTo(date2);
                }
            });
            for(Map<String,String> map : compareList) {
                ReturnList.add(map);
            }
        }
        return ReturnList;
    }

    /**
     * 根据参数名获取系统设置值
     * @param corpId
     * @param token
     * @return
     */
    public String getSysParamValueByMark(String corpId, String token, String mark) {
        RestClient restClient = new RestClient(true);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("corpId", corpId);
        paramMap.put("mark", mark);
        String type = configService.getConfigCache(mark, corpId,  token);
        if(type != null){
            return type;
        }
        return "";
    }

    public int revertWeekNumber(String week) {
        if(StringUtils.isBlank(week)){
            return 0;
        }
        if(week.contains("周一")){
            return 1;
        }
        if(week.contains("周二")){
            return 2;
        }
        if(week.contains("周三")){
            return 3;
        }
        if(week.contains("周四")){
            return 4;
        }
        if(week.contains("周五")){
            return 5;
        }
        if(week.contains("周六")){
            return 6;
        }
        if(week.contains("周日")){
            return 7;
        }
        return 0;
    }



    public String getCalendarInfo(String complateType , String isComplateId ,Calendar calendar,String searchStart,String searchEnd,String viewType,String userId,String corpId,List<String> maintainFieldValue,Map<String,List<CalendarDelete>> deletesMap,Map<String,CalendarCategory> categoryMap,Map<String,List<Calendar>> repeatsMap, String ingOrFinish,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();
        String calendarStart = CalendarUtils.getStrByDate(calendar.getStartDate(), "yyyy-MM-dd");
        String calendarEnd = calendar.getEndDate()==null ? calendarStart : CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
        //拼接日程事件
        String isMain = calendar.getIsMain();

        String duplicateType = calendar.getDuplicateType();
        if(!"no".equals(duplicateType) && "1".equals(isMain)){//主日程拼接重复日程json
            Date startCalendarDate = DateUtils.parseDate(calendarStart);
            Date endCalendarDate = DateUtils.parseDate(calendarEnd);
            Date startSearchDate = DateUtils.parseDate(searchStart);
            Date startEndDate = DateUtils.parseDate(searchEnd);
            if((startCalendarDate.getTime()<=startSearchDate.getTime() && endCalendarDate.getTime()>=startSearchDate.getTime())
                    || (startCalendarDate.getTime()>=startSearchDate.getTime()&&startCalendarDate.getTime()<=startEndDate.getTime())){
                result.append(this.setCalendarJson(complateType,isComplateId, calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,ingOrFinish,partFinishedMap));

            }

            String duplicateTypeValue = calendar.getDuplicateInterval();//重复间隔值
            String duplicateEndType = calendar.getDuplicateEndType();//重复结束类型
            String duplicateEndTypeValue = calendar.getDuplicateEndTypeValue();//重复结束类型值
            String weekMonthDuplicateType = calendar.getWeekMonthDuplicateType();//周/月重复类型
            List<Map<String, String>> list ;
            list = this.getDataMsg(duplicateType, duplicateTypeValue, duplicateEndType, duplicateEndTypeValue, calendarStart, calendarEnd==""?calendarStart:calendarEnd, searchEnd,weekMonthDuplicateType);

            if(list != null && !list.isEmpty()){
                String startDate = "";
                List<CalendarDelete> deletes = deletesMap.get(calendar.getId());
                //deletes = this.calendarDeleteDao.findByBelong(calendar.getId(), end);
                int flag = 0,flag1 = 0,flag2 = 0;
                String delFlag = "";
                for(int i=0;i<list.size();i++){
                    Map<String, String> map = list.get(i);
                    startDate = map.get("startDate");
                    if(deletes!=null && !deletes.isEmpty()){
                        for(int j=0;j<deletes.size();j++){
                            CalendarDelete delete = deletes.get(j);
                            if(delete != null){
                                delFlag = delete.getDeleteType();
                                if("current".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }else if("after".equals(delFlag)){
                                    flag = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(delete.getDeleteDate(), "yyyy-MM-dd"));
                                }
                                if(flag == 0){
                                    break;
                                }
                            }
                        }
                        if(flag==0 && "current".equals(delFlag)){
                            continue;
                        }else if(flag==0 && "after".equals(delFlag)){
                            break;
                        }
                    }
                    flag1 = CalendarUtils.compareDateStr(searchStart, startDate);
                    flag = CalendarUtils.compareDateStr(searchEnd, startDate);
                    if(flag1!=1 && flag!=2){
                        List<Calendar> repeats = new ArrayList<>();
                        //repeats = this.calendarDao.findCalendarByBelong(calendar.getId(), start, end);
                        repeats = repeatsMap.get(calendar.getId());
                        boolean equal = true;
                        if(repeats!=null && !repeats.isEmpty()){
                            for(int j=0;j<repeats.size();j++){
                                Calendar repeat = repeats.get(j);
                                flag2 = CalendarUtils.compareDateStr(startDate, CalendarUtils.getStrByDate(repeat.getStartDate(), "yyyy-MM-dd"));
                                if(flag2 == 0){
                                    equal = false;
                                    break;
                                }
                            }
                        }
                        if(equal){
                            result.append(",");
                            result.append(this.setCalendarJson(complateType,isComplateId, calendar, startDate, map.get("endDate"),"repeat",viewType,userId,corpId,maintainFieldValue,ingOrFinish,partFinishedMap));

                        }
                    }
                }
            }
        }else if(!"no".equals(duplicateType) && "0".equals(isMain)){//有编辑的子日程，返回回去
            Date startCalendarDate = DateUtils.parseDate(calendarStart);
            Date endCalendarDate = DateUtils.parseDate(calendarEnd);
            Date startSearchDate = DateUtils.parseDate(searchStart);
            Date startEndDate = DateUtils.parseDate(searchEnd);
            if((startCalendarDate.getTime()<=startSearchDate.getTime() && endCalendarDate.getTime()>=startSearchDate.getTime())
                    || (startCalendarDate.getTime()>=startSearchDate.getTime()&&startCalendarDate.getTime()<=startEndDate.getTime())){
                result.append(this.setCalendarJson(complateType,isComplateId, calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,ingOrFinish,partFinishedMap));

            }
        }else{
            result.append(this.setCalendarJson(complateType,isComplateId, calendar, calendarStart, calendarEnd,"",viewType,userId,corpId,maintainFieldValue,ingOrFinish,partFinishedMap));

        }
        return result.toString();
    }

    private String setCalendarJson(String complateType, String isComplateId,Calendar calendar, String startDate, String endDate,String repeatType,String viewType,String userId,String corpId,List<String> maintainFieldValue, String ingOrFinish,Map<String,List<String>> partFinishedMap){
        StringBuffer result = new StringBuffer();
        List<String> userList = Arrays.asList(userId.split(","));
        List<String> morePartList = new ArrayList<>();
        //查询当前用户是否已经完成该日程,如果complateType为4是不需要查询完成状况
        boolean isComplate = false;
        if(!StringUtils.equals(complateType, "4")) {
            // 指定日程标记完成参与人ID集合
//            List<String> partIdList = calendarFinishedDao.findPartId(calendar.getId());
            List<String> partIdList = partFinishedMap.get(calendar.getId());
            // 20210830 日程标记功能：判断当前用户是否标记完成日程
            if ("share".equals(viewType)) {
                // 共享日程判断日程是否完成判断的是创建人是否完成
                if (null != partIdList && partIdList.size() > 0) {
                    if (partIdList.contains(calendar.getCalendarOwner())) {
                        isComplate = true;
                    }
                }
                if(StringUtils.null2String(calendar.getCalendarCategory()).contains("_part")) {//参与日程
                    if (null != partIdList && partIdList.size() > 0) {
                        if (partIdList.contains(userId)) {
                            isComplate = true;
                        }
                    }
                }
            } else {
                if (null != partIdList && partIdList.size() > 0) {
                    if (partIdList.contains(userId)) {
                        isComplate = true;
                    }
                }
            }
            // isComplate = StringUtils.equals("1", calendar.getIsComplate())?true:false;
            if(StringUtils.isNotEmpty(calendar.getStartDate().toString())) {
                String calendarStart = DateUtils.formatDate(calendar.getStartDate(),"yyyy-MM-dd");
                if(!StringUtils.equals(calendarStart, startDate)) {
                    isComplate = false;
                }
            }
        }

        boolean isRealCreator = StringUtils.equals(StringUtils.null2String(calendar.getCreatedBy()), userId);
        if(StringUtils.equals("ing", ingOrFinish)) {
            if(isComplate == false) {
                result.append("{mainId:'" + calendar.getId() + "',"
                        + "title:'" + calendar.getTitle().replace("\\","\\\\").replace("'","\\'") + "'," +
                        "secdatacode:'"+calendar.getSecdatacode()+"',"
                        + "isMain:'" + calendar.getIsMain() + "',"
                        + "calendarOwner:'" + calendar.getCalendarOwner() + "',"
                        + "showOwner:'" + calendar.getCalendarOwner() + "',"
                        + "isComplate:'" + isComplate + "',"
                        + "content:'" + (calendar.getContent() == null ? "" : calendar.getContent().replace("\\","\\\\").replace("'","\\'")) + "',"
                        + "address:'" + (calendar.getAddress() == null ? "" : calendar.getAddress().replace("\\","\\\\").replace("'","\\'")) + "',"
                        + "isRealCreator:'" + isRealCreator + "'," //是否是日程创建人
                        + "isDuplicate:'" + calendar.getDuplicateType() + "',");
                if("1".equals(calendar.getIsAllDay())){//全天日程
                    result.append("allDay:true,"
                            + "start:'" + startDate + "',"
                            + "startTime:'"+ 0 +"'," // 全天日程开始时间设置为0，显示在上午区域中
                            + "startWeek: '" + 0 +"',"  // 全天日程开始时间设置为0，标题前不显示时间
                            + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm: '"+ 1 +"',"); // 全天日程默认显示在上午
                }else if (StringUtils.isNotBlank(calendar.getSetTimeFlag())) { // 上午/下午模式
                    String startTime = "";
                    String endTime = "";
                    int startTimeIntVal=0;
                    int endTimeIntVal=0;
                    if("1".equals(calendar.getSetTimeFlag())){
                        startTime="09:00";
                        startTimeIntVal=32400;
                        endTime = "12:00";
                        endTimeIntVal=43200;
                    }else{
                        startTime="14:00";
                        startTimeIntVal=50400;
                        endTime = "18:00";
                        endTimeIntVal=64800;
                    }

                    result.append("allDay:false,"
                            + "start:'" + startDate + "T" + startTime + "',"
                            + "end:'" + endDate + "T" + endTime + "',"
                            + "startTime:'"+ startTimeIntVal +"'," // 全天日程开始时间设置为0，显示在上午区域中
                            + "startWeek: '" + 0 +"',"  // 上午/下午模式日程开始时间设置为0，标题前不显示时间
                            + "endTime:'"+ endTimeIntVal +"'," //
                            + "amOrPm:'" + 1 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm: '"+ (Integer.parseInt(calendar.getSetTimeFlag())<=0? "0":"1") +"',"); // 上午/下午模式中日程所处位置
                }else{
                    String startTime = CalendarUtils.getTime(calendar.getStartTime());
                    String endTime = CalendarUtils.getTime(calendar.getEndTime());
                    result.append("allDay:false,start:'" + startDate + "T" + startTime + "',"
                            + "end:'" + endDate + "T" + endTime + "',"
                            + "startTime:'"+ calendar.getStartTime() +"',"
                            + "startWeek: '" + startDate + " " + startTime + "'," // 日程开始时间，用于标题前显示
                            + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm:'"+(Integer.parseInt(startTime.split(":")[0]) >= 12? "0": "1")+"',");
                }
                if("repeat".equals(repeatType) || "0".equals(calendar.getIsMain())){
                    result.append("repeat:'1',");
                    if("1".equals(calendar.getIsMain())){
                        result.append("id:'" + calendar.getId() + "',");
                    }else{
                        result.append("id:'" + calendar.getBelongCalendar() + "',");
                    }
                    result.append("dragable:false,");
                }else{
                    result.append("repeat:'0',").append("id:'" + calendar.getId() + "',");
                }
                CalendarCategory category = new CalendarCategory();
                if(!userId.equals(calendar.getCalendarOwner()) && !"share".equals(viewType)){//参与日程
                    List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
                    if (CollectionUtils.isNotEmpty(categorys)) {
                        category = categorys.get(0);
                    }

                    result.append("isPart:'1',");
                }else{
                    category = this.calendarCategoryDao.getCategoryById(calendar.getCalendarCategory(), corpId);
                }
                if(category == null) {
                    return "";
                }
                if("share".equals(viewType)){
                    String fieldValue1 = StringUtils.null2String(calendar.getMaintainer());
                    String fieldValue2 = StringUtils.null2String(category.getMaintainer());
                    if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2))){
                        result.append("isMaintain:'1',");
                        if("repeat".equals(repeatType)){
                            if("1".equals(calendar.getIsMain())){
                                result.append("showEditMsg:'1',");
                            }else{
                                Calendar main = this.calendarDao.findById(calendar.getBelongCalendar()).get();
                                CalendarCategory cate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                                fieldValue1 = StringUtils.null2String(main.getMaintainer());
                                fieldValue2 = StringUtils.null2String(cate.getMaintainer());
                                if(maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2)){
                                    result.append("showEditMsg:'1',");
                                }
                            }
                        }
                    }else{
                        result.append("isMaintain:'0',");
                        if(!"repeat".equals(viewType) && "1".equals(calendar.getIsMain())){
                            result.append("dragable:false,");
                        }
                    }
                }
                if("-1".equals(calendar.getIsMain())) {
                    result.append("isMaintain:'-1',");
                }else if("-2".equals(calendar.getIsMain())) {
                    result.append("isMaintain:'-2',");
                }
                result.append("classfiy:'" + category.getId() + "',");
                result.append("classfiyName:'" + category.getName() + "',");
                String syncId = StringUtils.null2String(calendar.getSyncId());
                result.append("syncId:'" + syncId + "',");
                if(calendar.getDegreeOfImportance() == null) {
                    result.append("degreeOfImportance:'1',");
                }else {
                    result.append("degreeOfImportance:'"+calendar.getDegreeOfImportance()+"',");
                }
                if(isComplate){
                    result.append("color:'#3f3f3f'").append("}");
                }else {
                    result.append("color:'" + category.getBackColor() + "'").append("}");
                }
            }
        }else if(StringUtils.equals("finish", ingOrFinish)){
            if(isComplate == true) {
                result.append("{mainId:'" + calendar.getId() + "',"
                        + "title:'" + calendar.getTitle().replace("\\","\\\\").replace("'","\\'") + "',"
                        + "isMain:'" + calendar.getIsMain() + "',"
                        + "calendarOwner:'" + calendar.getCalendarOwner() + "',"
                        + "showOwner:'" + calendar.getCalendarOwner() + "',"
                        + "isComplate:'" + isComplate + "',"
                        + "content:'" + (calendar.getContent() == null ? "" : calendar.getContent().replace("\\","\\\\").replace("'","\\'")) + "',"
                        + "address:'" + (calendar.getAddress() == null ? "" : calendar.getAddress().replace("\\","\\\\").replace("'","\\'")) + "',"
                        + "isRealCreator:'" + isRealCreator + "'," //是否是日程创建人
                        + "isDuplicate:'" + calendar.getDuplicateType() + "',");
                if("1".equals(calendar.getIsAllDay())){//全天日程
                    result.append("allDay:true,"
                            + "start:'" + startDate + "',"
                            + "startTime:'"+ 0 +"'," // 全天日程开始时间设置为0，显示在上午区域中
                            + "startWeek: '" + 0 +"',"  // 全天日程开始时间设置为0，标题前不显示时间
                            + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm: '"+ 1 +"',");
                }else if (StringUtils.isNotBlank(calendar.getSetTimeFlag())) { // 上午/下午模式
                    String startTime = "";
                    String endTime = "";
                    int startTimeIntVal=0;
                    int endTimeIntVal=0;
                    if("1".equals(calendar.getSetTimeFlag())){
                        startTime="09:00";
                        startTimeIntVal=32400;
                        endTime = "12:00";
                        endTimeIntVal=43200;
                    }else{
                        startTime="14:00";
                        startTimeIntVal=50400;
                        endTime = "18:00";
                        endTimeIntVal=64800;
                    }
                    result.append("allDay:false,"
                            + "start:'" + startDate + "T" + startTime + "',"
                            + "end:'" + endDate + "T" + endTime + "',"
                            + "startTime:'"+ startTimeIntVal +"'," // 全天日程开始时间设置为0，显示在上午区域中
                            + "startWeek: '" + 0 +"',"  // 上午/下午模式日程开始时间设置为0，标题前不显示时间
                            + "endTime:'"+ endTimeIntVal +"'," //
                            + "amOrPm:'" + 1 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm: '"+ (Integer.parseInt(calendar.getSetTimeFlag())<=0? "0":"1") +"',"); // 上午/下午模式中日程所处位置
                }else{
                    String startTime = CalendarUtils.getTime(calendar.getStartTime());
                    String endTime = CalendarUtils.getTime(calendar.getEndTime());
                    result.append("allDay:false,start:'" + startDate + "T" + startTime + "',"
                            + "end:'" + endDate + "T" + endTime + "',"
                            + "startTime:'"+ calendar.getStartTime() +"',"
                            + "startWeek: '" + startDate + " " + startTime + "'," // 日程开始时间，用于标题前显示
                            + "amOrPm:'" + 0 + "'," // 20220113 标记是上午/下午模式日程。作用：月视图中，在日程试图中标题前增加上午/下午标记，类似于正常日程标题前显示的时间，实现原形图效果
                            + "isAmOrPm:'"+(Integer.parseInt(startTime.split(":")[0]) >= 12? "0": "1")+"',");
                }
                if("repeat".equals(repeatType) || "0".equals(calendar.getIsMain())){
                    result.append("repeat:'1',");
                    if("1".equals(calendar.getIsMain())){
                        result.append("id:'" + calendar.getId() + "',");
                    }else{
                        result.append("id:'" + calendar.getBelongCalendar() + "',");
                    }
                    result.append("dragable:false,");
                }else{
                    result.append("repeat:'0',").append("id:'" + calendar.getId() + "',");
                }
                CalendarCategory category = new CalendarCategory();
                if(!userId.equals(calendar.getCalendarOwner()) && !"share".equals(viewType)){//参与日程
                    List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
                    if (CollectionUtils.isNotEmpty(categorys)) {
                        category = categorys.get(0);
                    }
                    result.append("isPart:'1',");
                }else{
                    category = this.calendarCategoryDao.getCategoryById(calendar.getCalendarCategory(), corpId);
                }
                if(category == null) {
                    return "";
                }
                if("share".equals(viewType)){
                    String fieldValue1 = StringUtils.null2String(calendar.getMaintainer());
                    String fieldValue2 = StringUtils.null2String(category.getMaintainer());
                    if(!maintainFieldValue.isEmpty() && (maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2))){
                        result.append("isMaintain:'1',");
                        if("repeat".equals(repeatType)){
                            if("1".equals(calendar.getIsMain())){
                                result.append("showEditMsg:'1',");
                            }else{
                                Calendar main = this.calendarDao.findById(calendar.getBelongCalendar()).get();
                                CalendarCategory cate = this.calendarCategoryDao.findById(main.getCalendarCategory()).get();
                                fieldValue1 = StringUtils.null2String(main.getMaintainer());
                                fieldValue2 = StringUtils.null2String(cate.getMaintainer());
                                if(maintainFieldValue.contains(fieldValue1) || maintainFieldValue.contains(fieldValue2)){
                                    result.append("showEditMsg:'1',");
                                }
                            }
                        }
                    }else{
                        result.append("isMaintain:'0',");
                        if(!"repeat".equals(viewType) && "1".equals(calendar.getIsMain())){
                            result.append("dragable:false,");
                        }
                    }
                }
                if("-1".equals(calendar.getIsMain())) {
                    result.append("isMaintain:'-1',");
                }else if("-2".equals(calendar.getIsMain())) {
                    result.append("isMaintain:'-2',");
                }
                result.append("classfiy:'" + category.getId() + "',");
                result.append("classfiyName:'" + category.getName() + "',");
                String syncId = StringUtils.null2String(calendar.getSyncId());
                result.append("syncId:'" + syncId + "',");
                if(calendar.getDegreeOfImportance() == null) {
                    result.append("degreeOfImportance:'1',");
                }else {
                    result.append("degreeOfImportance:'"+calendar.getDegreeOfImportance()+"',");
                }
                if(isComplate){
                    result.append("color:'#3f3f3f'").append("}");
                }else {
                    result.append("color:'" + category.getBackColor() + "'").append("}");
                }
            }
        }

//        String resultStr = result.toString();
//        if(CollectionUtils.isNotEmpty(morePartList)){
//            Map<String,String> resultMap = (Map<String, String>) JSON.parse(resultStr);
//            resultStr = "";
//            for(String partUserId : morePartList){
//                resultMap.put("showOwner",partUserId);
//                resultStr = resultStr+","+JSON.toJSONString(resultMap);;
//            }
//            resultStr = resultStr.substring(1);
//        }

        return result.toString();
    }

    /**
     * 获取列表用户下的工作日程
     * @param leaderUserList 用户id list
     * @return cateList List<Map> 工作日程list
     *
     */
    public List<Map> getAllLeaderWorkCate(List<String> leaderUserList){
        StringBuffer sql = new StringBuffer();
        Map<String,Object> mapValue = new HashMap<String,Object>();
        sql.append(" select id,createdBy,code from oa_calendar_category where createdBy in (:createdBy) and name = '工作日程' ");
        mapValue.put("createdBy", leaderUserList);
        List<Map> cateList = super.findByListNativeQuery(sql.toString(), "",mapValue);
        return cateList;
    }

    /**
     * 查询某个主日程下被删除的子日程
     * @param calendarId
     * @param start
     * @return
     */
    public List<CalendarDelete> findByBelong(String calendarId, Date start) {
        List<CalendarDelete> deletes = calendarDeleteDao.findByBelong(calendarId, start);
        return deletes;
    }

    /**
     * 查询日程分类
     * @param calendarCategory
     * @param corpId
     * @return
     */
    public CalendarCategory findCategory(String calendarCategory, String corpId) {
        CalendarCategory category = this.calendarCategoryDao.getCategoryById(calendarCategory, corpId);
        return category;
    }

    /**
     * 查询某个主日程下被编辑过的子日程
     * @param calendarId
     * @param start
     * @param end
     * @return
     */
    public List<Calendar> findCalendarByBelong(String calendarId, Date start, Date end) {
        List<Calendar> calendar = this.calendarDao.findCalendarByBelong(calendarId, start, end);
        return calendar;
    }

    /**
     * 会议同步至日程
     * @param map
     * @return
     */
    public Calendar editSaveMeeting(Map<String,String> map,WebUser user) {
        Calendar calendar = null;
        String calendarId = map.get("calendarId");//日程id
        if(StringUtils.isBlank(calendarId)) {
            calendar = new Calendar();
            calendar.setId(UuidUtils.UUID());
        }else {
            calendar = this.findOne(calendarId);
        }
        String owner = map.get("owner");//日程拥有人id
        String title = map.get("title");//标题
        String startTimeStr = map.get("startTime");//开始时间
        String endTimeStr = map.get("endTime");//结束时间
        String content = map.get("content");//内容
        String address = map.get("address");//地址
        String attId = map.get("attId");//附件id
        String meetingId = map.get("meetingId");//会议数据id
        String meetingFormId = map.get("meetingFormId");//会议表单id
        String isRepeat = map.get("isRepeat");//是否是重复日程
        String duplicateType = map.get("duplicateType");//重复类型
        String duplicateInterval = map.get("duplicateInterval");//重复间隔值
        String duplicateEndType = map.get("duplicateEndType");//重复结束类型
        String duplicateEndTypeValue = map.get("duplicateEndTypeValue");//重复结束类型值
        String weekMonthDuplicateType = map.get("weekMonthDuplicateType");//月、周重复规则
        String partUserList = map.get("partUserList");//参与人json串
        String pushType = map.get("pushType");


        calendar.setTitle(title);
        calendar.setIsMain("1");
        calendar.setAddress(address);
        calendar.setContent(content);
        calendar.setCalendarOwner(owner);
        calendar.setDuplicateType("no");
        calendar.setDuplicateEndType("always");
        calendar.setExpiryReminder("yes");
        calendar.setExpiryReminderTime("30min");
        calendar.setRemindStyle("mobile,sms");
        calendar.setAttachment(attId);
        calendar.setCreatedBy(owner);
        String startDate = startTimeStr.substring(0,10);//开始日期
        String startTime = startTimeStr.substring(11,19);//开始时间
        String endDate = endTimeStr.substring(0,10);//结束日期
        String endTime = endTimeStr.substring(11,19);//结束时间
        calendar.setStartDate(DateUtils.parseDate(startDate,"yyyy-MM-dd"));
        calendar.setEndDate(DateUtils.parseDate(endDate,"yyyy-MM-dd"));
        calendar.setStartTime(CalendarUtils.getSeconds(startTime));
        calendar.setEndTime(CalendarUtils.getSeconds(endTime));
        calendar.setIsAllDay("0");
        calendar.setSyncModule("meeting_"+meetingFormId+"_"+pushType);
        calendar.setModuleDataId(meetingId);

        if("1".equals(isRepeat)){
            calendar.setDuplicateType(duplicateType);
            calendar.setDuplicateInterval(duplicateInterval);
            calendar.setDuplicateEndType(duplicateEndType);
            calendar.setDuplicateEndTypeValue(duplicateEndTypeValue);
            calendar.setWeekMonthDuplicateType(weekMonthDuplicateType);
        }

        String categoryId = null;
        List<Map> list = calendarCategoryService.ifSingleWork(owner);
        //如果已经有自定义的工作日程，直接取id
        if(CollectionUtils.isNotEmpty(list)) {
            categoryId = list.get(0).get("id").toString();
        }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
            CalendarCategory ca = new CalendarCategory();
            String newCategoryId = UuidUtils.UUID();
            ca.setId(newCategoryId);
            ca.setCreatedBy(owner);
            ca.setCode("singleWork");
            ca.setBackColor("#548dd4");
            ca.setCategory("calendarOwner");
            ca.setName("工作日程");
            ca.setSortNo(0);
            categoryId = ca.getId();
            //保存类别
            this.calendarCategoryService.save(ca);
        }
        calendar.setCalendarCategory(categoryId);
        String part = UuidUtils.UUID();
        calendar.setParticipant(part);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partUserList, "oa_calendar", "participant");
        String viewer = UuidUtils.UUID();
        calendar.setViewer(viewer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, "", "oa_calendar", "viewer");
        String maintainer = UuidUtils.UUID();
        calendar.setMaintainer(maintainer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, "", "oa_calendar", "maintainer");
        Calendar cal = super.save(calendar);

        /**做数据同步开始**/
        Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(user.getCorpId(),"calendarSync");
        String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
        //重复日程不同步
        if(calendarSync.contains("evoPortal")&& "no".equals(cal.getDuplicateType())){
            try {
                this.calendarSaveOrUpdateToEvoPortal(cal,user.getCorpId(),user.getJwtToken());
            }catch (Exception e){
                LOG.error("同步失败",e);
            }
        }
        /**做数据同步结束**/

        return cal;
    }

    /**
     * 值班同步至日程
     * @param map
     * @return
     */
    public Calendar editSaveDuty(Map<String,String> map,WebUser user) {
        Calendar calendar = null;
        String dutyId = map.get("dutyId");//排班数据id
        if(StringUtils.isBlank(dutyId)) {
            calendar = new Calendar();
            calendar.setId(UuidUtils.UUID());
        }else {
            calendar = calendarDao.findModuleCalendar(dutyId);
            if(calendar == null || calendar.getId()==null) {
                calendar = new Calendar();
                calendar.setId(UuidUtils.UUID());
            }
        }
        String owner = map.get("owner");//日程拥有人id
        String title = map.get("title");//标题
        String startTimeStr = map.get("startTime");//开始时间

        String content = map.get("content");//内容
        String address = map.get("address");//地址

        String isRemind = map.get("isRemind");
        String remindTime = map.get("remindTime");
        String participantUser = map.get("participantUser");
        calendar.setTitle(title);
        calendar.setIsMain("1");
        calendar.setAddress(address);
        calendar.setContent(content);
        calendar.setCalendarOwner(owner);
        calendar.setDuplicateType("no");
        calendar.setDuplicateEndType("always");

        calendar.setExpiryReminder(isRemind);
        calendar.setExpiryReminderTime(remindTime);

        String remindStyle = this.getCalendarRemind(user.getCorpId(),user.getJwtToken());
        calendar.setRemindStyle(remindStyle);

        calendar.setCreatedBy(user.getUserId());
        String startDate = startTimeStr.substring(0,10);//开始日期

        calendar.setStartDate(DateUtils.parseDate(startDate,"yyyy-MM-dd"));

        calendar.setIsAllDay("1");
        calendar.setModuleDataId(dutyId);
        calendar.setDegreeOfImportance("1");//重要程度
        String categoryId = null;
        List<Map> list = calendarCategoryService.ifSingleWork(owner);
        //如果已经有自定义的工作日程，直接取id
        if(CollectionUtils.isNotEmpty(list)) {
            categoryId = list.get(0).get("id").toString();
        }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
            CalendarCategory ca = new CalendarCategory();
            String newCategoryId = UuidUtils.UUID();
            ca.setId(newCategoryId);
            ca.setCreatedBy(owner);
            ca.setCode("singleWork");
            ca.setBackColor("#548dd4");
            ca.setCategory("calendarOwner");
            ca.setName("工作日程");
            ca.setSortNo(0);
            categoryId = ca.getId();
            //保存类别
            this.calendarCategoryService.save(ca);
        }
        calendar.setCalendarCategory(categoryId);
        String part = UuidUtils.UUID();
        calendar.setParticipant(part);
        String partJson = "";
        if(StringUtils.isNotBlank(participantUser)) {
            List<Map<String,Object>> userList = userApiService.getUserList(participantUser, user.getCorpId(), "", user.getJwtToken());
            partJson = "[";
            for(Map<String,Object> partUser : userList) {
                partJson = partJson+"{\"scopeName\":\""+partUser.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+partUser.get("id")+"\",\"title\":\""+partUser.get("userName")+"\"},";
            }
            if(partJson.length()>10) {
                partJson = partJson.substring(0, partJson.length()-1);
            }
            partJson = partJson+"]";

        }
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partJson, "oa_calendar", "participant");
        String viewer = UuidUtils.UUID();
        calendar.setViewer(viewer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, "", "oa_calendar", "viewer");
        String maintainer = UuidUtils.UUID();
        calendar.setMaintainer(maintainer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, "", "oa_calendar", "maintainer");
        Calendar cal = super.save(calendar);

        /**做数据同步开始**/
        Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(user.getCorpId(),"calendarSync");
        String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
        //重复日程不同步
        if(calendarSync.contains("evoPortal") && "no".equals(cal.getDuplicateType())){
            try {
                this.calendarSaveOrUpdateToEvoPortal(cal,user.getCorpId(),user.getJwtToken());
            }catch (Exception e){
                LOG.error("同步日程失败",e);
            }
        }
        /**做数据同步结束**/

        return cal;
    }

    /**
     * 督查督办同步至日程
     * @param map
     * @return
     */
    @Transactional
    public Calendar editSaveSupervise(Map<String,String> map,WebUser user) {
        Calendar calendar = JSONObject.parseObject(JSONObject.toJSONString(map),Calendar.class);
        String moduleDataId = calendar.getModuleDataId();//业务数据id

        Calendar moduleCalendar = calendarDao.findModuleCalendar(moduleDataId);
        if(moduleCalendar != null && moduleCalendar.getId()!=null) {
            calendar.setId(moduleCalendar.getId());
        }else{
            calendar.setId(UuidUtils.UUID());
        }
        String participantUser = map.get("participantUser");

        String categoryId = null;
        List<Map> list = calendarCategoryService.ifSingleWork(calendar.getCalendarOwner());
        //如果已经有自定义的工作日程，直接取id
        if(CollectionUtils.isNotEmpty(list)) {
            categoryId = list.get(0).get("id").toString();
        }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
            CalendarCategory ca = new CalendarCategory();
            String newCategoryId = UuidUtils.UUID();
            ca.setId(newCategoryId);
            ca.setCreatedBy(calendar.getCalendarOwner());
            ca.setCode("singleWork");
            ca.setBackColor("#548dd4");
            ca.setCategory("calendarOwner");
            ca.setName("工作日程");
            ca.setSortNo(0);
            categoryId = ca.getId();
            //保存类别
            this.calendarCategoryService.save(ca);
        }
        calendar.setCalendarCategory(categoryId);
        String part = UuidUtils.UUID();
        calendar.setParticipant(part);
        String partJson = "";
        if(StringUtils.isNotBlank(participantUser)) {
            List<Map<String,Object>> userList = userApiService.getUserList(participantUser, user.getCorpId(), "", user.getJwtToken());
            partJson = "[";
            for(Map<String,Object> partUser : userList) {
                partJson = partJson+"{\"scopeName\":\""+partUser.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+partUser.get("id")+"\",\"title\":\""+partUser.get("userName")+"\"},";
            }
            if(partJson.length()>10) {
                partJson = partJson.substring(0, partJson.length()-1);
            }
            partJson = partJson+"]";

        }
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partJson, "oa_calendar", "participant");
        String viewer = UuidUtils.UUID();
        calendar.setViewer(viewer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, "", "oa_calendar", "viewer");
        String maintainer = UuidUtils.UUID();
        calendar.setMaintainer(maintainer);
        this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, "", "oa_calendar", "maintainer");
        Calendar cal = super.save(calendar);

        /**做数据同步开始**/
        Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(user.getCorpId(),"calendarSync");
        String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
        //重复日程不同步
        if(calendarSync.contains("evoPortal") && "no".equals(cal.getDuplicateType())){
            try {
                this.calendarSaveOrUpdateToEvoPortal(cal,user.getCorpId(),user.getJwtToken());
            }catch (Exception e){
                LOG.error("同步日程失败",e);
            }
        }
        /**做数据同步结束**/
        return cal;
    }

    /**
     * 对数据进行校验
     *
     */
    public String verifyEvoPortalData(Map<String,String> map){
        String title = map.get("title");//标题
        String dutyId = map.get("dutyId");//三方数据id
        String startTime = map.get("startTime");//开始时间
        String endTime = map.get("endTime");//结束时间
        String startDate = map.get("startDate");//开始日期
        String endDate = map.get("endDate");//结束日期
        String content = map.get("content");//内容
        String address = map.get("address");//地址
        String owner = map.get("owner");//日程拥有人id
        String remindTime = map.get("remindTime");
        String participantUser = map.get("participantUser");
        String duplicateType = map.get("duplicateType");
        String duplicateEndType = map.get("duplicateEndType");
        String duplicateEndTypeValue = map.get("duplicateEndTypeValue");
        String duplicateTypeValue = map.get("duplicateTypeValue");
        String weekMonthDuplicateType = map.get("weekMonthDuplicateType");

//        Pattern pattern = Pattern.compile("^([\\u4E00-\\u9FA5]|\\w|\\>|\\/|\\.|\\·|\\~|\\@|\\（|\\—|\\）|\\(|\\)|\\-|\\－|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\。|\\、|\\《|\\》|\\；|\\:|\\;|\\？|\\\"|\\”|\\“|\\?)*([\\u4E00-\\u9FA5]|\\w|\\>|\\/|\\.|\\·|\\~|\\@| |\\（|\\\"|\\”|\\“|\\）|\\(|\\)|\\-|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\。|\\、|\\—|\\《|\\》|\\；|\\：|\\;|\\？|\\?)*([\\u4E00-\\u9FA5]|\\w|\\/|\\>|\\.|\\·|\\~|\\@|\\（|\\）|\\(|\\)|\\-|\\－|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\\"|\\”|\\“|\\。|\\、|\\《|\\》|\\；|\\：|\\;|\\？|\\—|\\?)+$");

        String regexp = "[0-9]{4}-[0-9]{2}-[0-9]{2}";

        if(StringUtils.isEmpty(owner)){
            return "日程所属人不能为空";
        }

        if(StringUtils.isEmpty(dutyId)){
            return "数据id不能为空";
        }

        //标题不能为空
        if(StringUtils.isEmpty(title)){
            return "标题不能为空";
        }
        //超过部分舍弃
        if(title.length()>200){
            title = title.substring(0,200);
        }
        //标题正则验证
//        if(StringUtils.isNoneBlank(title) && !pattern.matcher(title).matches()){
//            return "标题为中文/字母/数字/符号";
//        }
        map.put("title",title);

        //地址验证
//        if(StringUtils.isNoneBlank(address) && !pattern.matcher(address).matches()){
//            return "地址为中文/字母/数字/符号";
//        }
        //超过部分舍弃
        if(StringUtils.isNoneBlank(address) && address.length()>50){
            address = address.substring(0,50);
            map.put("address",address);
        }

        //内容验证
//        if(StringUtils.isNoneBlank(content) && !pattern.matcher(content).matches()){
//            return "内容为中文/字母/数字/符号";
//        }
        //超过部分舍弃
        if(StringUtils.isNoneBlank(content) && content.length()>200){
            content = content.substring(0,200);
            map.put("content",content);
        }

        //开始日期
        if(StringUtils.isEmpty(startDate)){
            return "开始日期不能为空";
        }
        //结束日期
        if(StringUtils.isEmpty(endDate)){
            return "结束日期不能为空";
        }
        //开始日期格式是否匹配
        if(!Pattern.compile(regexp).matcher(startDate).matches()){
            return "开始日期格式不正确";
        }
        //结束日期格式是否匹配
        if(!Pattern.compile(regexp).matcher(endDate).matches()){
            return "结束日期格式不正确";
        }
        //开始时间
        if(StringUtils.isEmpty(startTime)){
            return "开始时间不能为空";
        }
        //开始时间
        if(StringUtils.isEmpty(endTime)){
            return "结束时间不能为空";
        }
        //结束时间
        if(!ValidateUtils.validateInt(endTime)){
            return "结束时间格式不正确";
        }

        if(!ValidateUtils.validateInt(startTime)){
            return "开始时间格式不正确";
        }

        return null;

    }

    /**
     * evoportal同步日程数据
     *
     */
    public OperationResult editSaveEvoportal(Map<String,String> map){
        try {
            Calendar calendar;
            CalendarThird calendarThird;
            String dutyId = map.get("dutyId");//evo数据id
            if(StringUtils.isEmpty(dutyId)){
                LOG.error("同步失败，数据Id不能为空");
                return OperationResult.buildFailureResult("同步失败，数据Id不能为空");
            }

            LOG.debug("evoPortal同步过来的信息:"+JSON.toJSONString(map));

            //这里获取token
            String token = map.get("token");

            calendarThird = calendarThirdService.getCalendarThirdByThirdId(dutyId,"evoPortal");
            String type = "edit";
            if(calendarThird == null || calendarThird.getId()==null || StringUtils.isEmpty(calendarThird.getCalendarId())) {
                calendar = new Calendar();
                calendar.setId(UuidUtils.UUID());
                type = "add";
            }else{
                calendar = this.findOne(calendarThird.getCalendarId());
                if(calendar==null){
                    calendar = new Calendar();
                }
            }
            String title = map.get("title");//标题
            String owner = map.get("owner");//日程拥有人id
            String startTime = map.get("startTime");//开始时间
            String endTime = map.get("endTime");//开始时间
            String startDate = map.get("startDate");//开始时间
            String endDate = map.get("endDate");//开始时间
            String content = map.get("content");//内容
            String address = map.get("address");//地址
            String remindTime = map.get("remindTime");

            String participantUser = map.get("participantUser");

            String duplicateType = map.get("duplicateType");
            String duplicateEndType = map.get("duplicateEndType");
            String duplicateEndTypeValue = map.get("duplicateEndTypeValue");
            String duplicateTypeValue = map.get("duplicateTypeValue");
            String weekMonthDuplicateType = map.get("weekMonthDuplicateType");
            String corpId = map.get("corpId");

            Map userMap = userApiService.getUserByType("loginNo", owner, corpId,token);
            if(userMap==null || userMap.get("id")==null){
                LOG.error("同步失败,日程所属人为空！");
                return OperationResult.buildFailureResult("同步失败,日程所属人为空！");
            }

            String part = UuidUtils.UUID();
            String partJson = "";
            if(StringUtils.isNotBlank(participantUser)) {
                partJson = "[";
                String[] participantUserArr = participantUser.split(",");
                String errorMessage="";
                for(String loginName : participantUserArr){
                    Map partUserMap = userApiService.getUserByType("loginNo", loginName, corpId,token);
                    if(partUserMap==null || partUserMap.get("id")==null){
                        LOG.error("同步失败,部分参与人为空！");
                        errorMessage = "同步失败,部分参与人为空！";
                        break;
//                        return OperationResult.buildFailureResult("同步失败,部分参与人为空！");
                    }
                    partJson = partJson+"{\"scopeName\":\""+partUserMap.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+partUserMap.get("id")+"\",\"title\":\""+partUserMap.get("userName")+"\"},";
                }
                if(StringUtils.isNotEmpty(errorMessage)){
                    return OperationResult.buildFailureResult(errorMessage);
                }
                LOG.error("方法还在执行？");
                if(partJson.length()>10) {
                    partJson = partJson.substring(0, partJson.length()-1);
                }
                partJson = partJson+"]";
            }


            owner = StringUtils.null2String(userMap.get("id"));

            //重复日程
            if(StringUtils.isEmpty(duplicateType)){
                duplicateType = "no";
            }
            calendar.setDuplicateType(duplicateType);
            if("no".equals(duplicateType)){
                calendar.setDuplicateEndType("always");
            }else{
                calendar.setDuplicateEndType(duplicateEndType);

            }
            calendar.setDuplicateEndTypeValue(duplicateEndTypeValue);
            calendar.setDuplicateInterval(duplicateTypeValue);
            calendar.setWeekMonthDuplicateType(weekMonthDuplicateType);


            calendar.setTitle(title);
            calendar.setIsMain("1");
            calendar.setAddress(address);
            calendar.setContent(content);
            calendar.setCalendarOwner(owner);
            calendar.setExpiryReminder("yes");
            //提醒时间
            if("0".equals(remindTime)){
                calendar.setExpiryReminderTime("punctuality");
            }else if("5".equals(remindTime)){
                calendar.setExpiryReminderTime("5min");
            }else if("10".equals(remindTime)){
                calendar.setExpiryReminderTime("10min");
            }else if("30".equals(remindTime)){
                calendar.setExpiryReminderTime("30min");
            }else if("60".equals(remindTime)){
                calendar.setExpiryReminderTime("1hour");
            }else if("180".equals(remindTime)){
                calendar.setExpiryReminderTime("3hour");
            }else if("360".equals(remindTime)){
                calendar.setExpiryReminderTime("6hour");
            }else if("1440".equals(remindTime)){
                calendar.setExpiryReminderTime("1day");
            }else{
                calendar.setExpiryReminderTime("notRemind");
            }
            String remindStyle = this.getCalendarRemind(corpId,token);
            calendar.setRemindStyle(remindStyle);

            calendar.setCreatedBy(owner);
            calendar.setStartDate(DateUtils.parseDate(startDate,DateUtils.DEFAULT_DATE_FORMAT));
            calendar.setEndDate(DateUtils.parseDate(endDate,DateUtils.DEFAULT_DATE_FORMAT));
            calendar.setStartTime(Integer.parseInt(startTime));
            calendar.setEndTime(Integer.parseInt(endTime));
            calendar.setIsAllDay("0");
            calendar.setDegreeOfImportance("1");//重要程度
            calendar.setCorpId(corpId);

            String categoryId = null;
            List<Map> list = calendarCategoryService.ifSingleWork(owner);
            //如果已经有自定义的工作日程，直接取id
            if(CollectionUtils.isNotEmpty(list)) {
                categoryId = list.get(0).get("id").toString();
            }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
                CalendarCategory ca = new CalendarCategory();
                String newCategoryId = UuidUtils.UUID();
                ca.setId(newCategoryId);
                ca.setCreatedBy(owner);
                ca.setCode("singleWork");
                ca.setBackColor("#548dd4");
                ca.setCategory("calendarOwner");
                ca.setName("工作日程");
                ca.setSortNo(0);
                categoryId = ca.getId();
                //保存类别
                this.calendarCategoryService.save(ca);
            }
            calendar.setCalendarCategory(categoryId);
            calendar.setParticipant(part);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partJson, "oa_calendar", "participant");
            String viewer = UuidUtils.UUID();
            calendar.setViewer(viewer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, "", "oa_calendar", "viewer");
            String maintainer = UuidUtils.UUID();
            calendar.setMaintainer(maintainer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, "", "oa_calendar", "maintainer");
            Calendar cal = super.save(calendar);
            if("add".equals(type)){
                /**新增**/
                if(calendarThird!=null && calendarThird.getThirdId()!=null){
                    calendarThird.setModuleCode("evoPortal");
                    calendarThird.setCalendarId(cal.getId());
                    calendarThird.setStatusMsg("evoPortal新增office成功");
                    calendarThird.setCorpId(corpId);
                }else{
                    calendarThird = new CalendarThird();
                    calendarThird.setCalendarId(cal.getId());
                    calendarThird.setThirdId(dutyId);
                    calendarThird.setModuleCode("evoPortal");
                    calendarThird.setStatusMsg("evoPortal新增office成功");
                    calendarThird.setCorpId(corpId);
                }
            }else{
                /**修改**/
                calendarThird.setStatusMsg("evoPortal修改office成功");
            }

            calendarThirdService.save(calendarThird);

            return OperationResult.buildSuccessResult("同步成功",cal.getId());
        }catch (Exception e){
            LOG.error("同步失败",e);
            return OperationResult.buildFailureResult("同步失败");
        }
    }


    /**
     * 日程同步
     */
    public OperationResult editSaveCalendar(Map<String,String> map){
        try {
            Calendar calendar;
            CalendarThird calendarThird;
            String dutyId = map.get("dutyId");//evo数据id
            if(StringUtils.isEmpty(dutyId)){
                LOG.error("同步失败，数据Id不能为空");
                return OperationResult.buildFailureResult("同步失败，数据Id不能为空");
            }

            LOG.debug("同步过来的信息:"+JSON.toJSONString(map));

            //这里获取token
            String token = map.get("token");
            String moduleCode = map.get("moduleCode");
            calendarThird = calendarThirdService.getCalendarThirdByThirdId(dutyId,moduleCode);

            String type = "edit";
            if(calendarThird == null || calendarThird.getId()==null || StringUtils.isEmpty(calendarThird.getCalendarId())) {
                calendar = new Calendar();
                calendar.setId(UuidUtils.UUID());
                type = "add";
            }else{
                calendar = this.findOne(calendarThird.getCalendarId());
                if(calendar==null){
                    calendar = new Calendar();
                }
            }
            String title = map.get("title");//标题
            String owner = map.get("owner");//日程拥有人id
            String startTime = map.get("startTime");//开始时间
            String endTime = map.get("endTime");//开始时间
            String startDate = map.get("startDate");//开始时间
            String endDate = map.get("endDate");//开始时间
            String content = map.get("content");//内容
            String address = map.get("address");//地址
            String remindTime = map.get("remindTime");

            String participantUser = map.get("participantUser");

            String viewerUser = map.get("viewerUser");
            String maintainerUser = map.get("maintainerUser");

            String duplicateType = map.get("duplicateType");
            String duplicateEndType = map.get("duplicateEndType");
            String duplicateEndTypeValue = map.get("duplicateEndTypeValue");
            String duplicateTypeValue = map.get("duplicateTypeValue");
            String weekMonthDuplicateType = map.get("weekMonthDuplicateType");
            String corpId = map.get("corpId");

            Map userMap = userApiService.getUserByType("loginNo", owner, corpId,token);
            if(userMap==null || userMap.get("id")==null){
                LOG.error("同步失败,日程所属人为空！");
                return OperationResult.buildFailureResult("同步失败,日程所属人为空！");
            }

            String part = UuidUtils.UUID();
            String partJson = "";
            if(StringUtils.isNotBlank(participantUser)) {
                partJson = "[";
                String[] participantUserArr = participantUser.split(",");
                String errorMessage="";
                for(String loginName : participantUserArr){
                    if(StringUtils.equals(loginName,owner)){
                        continue;
                    }
                    Map partUserMap = userApiService.getUserByType("loginNo", loginName, corpId,token);
                    if(partUserMap==null || partUserMap.get("id")==null){
                        LOG.error("同步失败,部分参与人为空！");
                        errorMessage = "同步失败,部分参与人为空！";
                        break;
                    }
                    partJson = partJson+"{\"scopeName\":\""+partUserMap.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+partUserMap.get("id")+"\",\"title\":\""+partUserMap.get("userName")+"\"},";
                }
                if(StringUtils.isNotEmpty(errorMessage)){
                    return OperationResult.buildFailureResult(errorMessage);
                }
                LOG.debug("方法还在执行？");
                if(partJson.length()>10) {
                    partJson = partJson.substring(0, partJson.length()-1)+"]";
                }else{
                    partJson = "";
                }
            }

            String viewer = UuidUtils.UUID();
            String viewerJson = "";
            if(StringUtils.isNotBlank(viewerUser)) {
                viewerJson = "[";
                String[] viewerUserArr = viewerUser.split(",");
                String errorMessage="";
                for(String loginName : viewerUserArr){
                    if(StringUtils.equals(loginName,owner)){
                        continue;
                    }
                    Map viewerUserMap = userApiService.getUserByType("loginNo", loginName, corpId,token);
                    if(viewerUserMap==null || viewerUserMap.get("id")==null){
                        LOG.error("同步失败,部分可查看人为空！");
                        errorMessage = "同步失败,部分可查看人为空！";
                        break;
                    }
                    viewerJson = viewerJson+"{\"scopeName\":\""+viewerUserMap.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+viewerUserMap.get("id")+"\",\"title\":\""+viewerUserMap.get("userName")+"\"},";
                }
                if(StringUtils.isNotEmpty(errorMessage)){
                    return OperationResult.buildFailureResult(errorMessage);
                }
                LOG.error("方法还在执行？");
                if(viewerJson.length()>10) {
                    viewerJson = viewerJson.substring(0, viewerJson.length()-1)+"]";
                }else{
                    viewerJson = "";
                }
            }


            String maintainer = UuidUtils.UUID();
            String maintainerJson = "";
            if(StringUtils.isNotBlank(maintainerUser)) {
                maintainerJson = "[";
                String[] maintainerUserArr = maintainerUser.split(",");
                String errorMessage="";
                for(String loginName : maintainerUserArr){
                    if(StringUtils.equals(loginName,owner)){
                        continue;
                    }
                    Map maintainerUserMap = userApiService.getUserByType("loginNo", loginName, corpId,token);
                    if(maintainerUserMap==null || maintainerUserMap.get("id")==null){
                        LOG.error("同步失败,部分可维护人为空！");
                        errorMessage = "同步失败,部分可维护人为空！";
                        break;
                    }
                    maintainerJson = maintainerJson+"{\"scopeName\":\""+maintainerUserMap.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+maintainerUserMap.get("id")+"\",\"title\":\""+maintainerUserMap.get("userName")+"\"},";
                }
                if(StringUtils.isNotEmpty(errorMessage)){
                    return OperationResult.buildFailureResult(errorMessage);
                }
                LOG.debug("方法还在执行？");
                if(maintainerJson.length()>10) {
                    maintainerJson = maintainerJson.substring(0, maintainerJson.length()-1)+"]";
                }else{
                    maintainerJson = "";
                }
            }

            owner = StringUtils.null2String(userMap.get("id"));

            //重复日程
            if(StringUtils.isEmpty(duplicateType)){
                duplicateType = "no";
            }
            calendar.setDuplicateType(duplicateType);
            if("no".equals(duplicateType)){
                calendar.setDuplicateEndType("always");
            }else{
                calendar.setDuplicateEndType(duplicateEndType);

            }
            calendar.setDuplicateEndTypeValue(duplicateEndTypeValue);
            calendar.setDuplicateInterval(duplicateTypeValue);
            calendar.setWeekMonthDuplicateType(weekMonthDuplicateType);


            calendar.setTitle(title);
            calendar.setIsMain("1");
            calendar.setAddress(address);
            calendar.setContent(content);
            calendar.setCalendarOwner(owner);
            calendar.setExpiryReminder("yes");
            //提醒时间
            if(StringUtils.isEmpty(remindTime)){
                remindTime = "10min";
            }
            calendar.setExpiryReminderTime(remindTime);
            String remindStyle = this.getCalendarRemind(corpId,token);
            calendar.setRemindStyle(remindStyle);

            calendar.setCreatedBy(owner);
            calendar.setStartDate(DateUtils.parseDate(startDate,DateUtils.DEFAULT_DATE_FORMAT));
            calendar.setEndDate(DateUtils.parseDate(endDate,DateUtils.DEFAULT_DATE_FORMAT));
            calendar.setStartTime(Integer.parseInt(startTime));
            calendar.setEndTime(Integer.parseInt(endTime));
            calendar.setIsAllDay("0");
            calendar.setDegreeOfImportance("1");//重要程度
            calendar.setCorpId(corpId);

            String categoryId = null;
            List<Map> list = calendarCategoryService.ifSingleWork(owner);
            //如果已经有自定义的工作日程，直接取id
            if(CollectionUtils.isNotEmpty(list)) {
                categoryId = list.get(0).get("id").toString();
            }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
                CalendarCategory ca = new CalendarCategory();
                String newCategoryId = UuidUtils.UUID();
                ca.setId(newCategoryId);
                ca.setCreatedBy(owner);
                ca.setCode("singleWork");
                ca.setBackColor("#548dd4");
                ca.setCategory("calendarOwner");
                ca.setName("工作日程");
                ca.setSortNo(0);
                categoryId = ca.getId();
                //保存类别
                this.calendarCategoryService.save(ca);
            }
            calendar.setCalendarCategory(categoryId);
            calendar.setParticipant(part);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partJson, "oa_calendar", "participant");
            calendar.setViewer(viewer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, viewerJson, "oa_calendar", "viewer");
            calendar.setMaintainer(maintainer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, maintainerJson, "oa_calendar", "maintainer");
            Calendar cal = super.save(calendar);
            if("add".equals(type)){
                /**新增**/
                if(calendarThird!=null && calendarThird.getThirdId()!=null){
                    calendarThird.setModuleCode(moduleCode);
                    calendarThird.setCalendarId(cal.getId());
                    calendarThird.setStatusMsg(moduleCode+"新增office成功");
                    calendarThird.setCorpId(corpId);
                }else{
                    calendarThird = new CalendarThird();
                    calendarThird.setCalendarId(cal.getId());
                    calendarThird.setThirdId(dutyId);
                    calendarThird.setModuleCode(moduleCode);
                    calendarThird.setStatusMsg(moduleCode+"新增office成功");
                    calendarThird.setCorpId(corpId);
                }
            }else{
                /**修改**/
                calendarThird.setStatusMsg(moduleCode+"修改office成功");
            }
            calendarThirdService.save(calendarThird);
            List userList = new ArrayList();
            WebsocketUtils.sendMessageByIds(userList,WebsocketConstant.MSGUMC,WebsocketConstant.UMC,WebsocketConstant.MSGPOP,WebsocketConstant.CALENDAR);
            return OperationResult.buildSuccessResult("同步成功",cal.getId());
        }catch (Exception e){
            LOG.error("同步失败",e);
            return OperationResult.buildFailureResult("同步失败");
        }
    }


    /**
     * 判断给定用户是否在该日程的维护权限中
     *
     * @param userId 用户id
     * @param calendar 日程实体类
     *
     * @return yes 在维护权限  no 不在维护权限
     */
    public String judgeShareCanEdit(String userId,Calendar calendar){
        //判断是否在日程的可维护人字段中
        List<String> canEditList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope","oa_calendar","maintainer",calendar.getMaintainer());
        if(canEditList.contains(userId)){
            return "yes";
        }

        //判断分类是否可维护
        //获取分类
        String categoryId = calendar.getCalendarCategory();

        CalendarCategory calendarCategory = calendarCategoryService.findOne(categoryId);
        if(calendarCategory!=null && StringUtils.isNotBlank(calendarCategory.getMaintainer())){
            //查询分类可维护人
            List<String> categoryEditList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope","oa_calendar_category","maintainer",calendarCategory.getMaintainer());

            if(categoryEditList.contains(userId)){
                return "yes";
            }
        }

        return "no";

    }

    /**
     * 判断日程是否有参与人
     * @param calendarId 日程Id
     * @return boolean true 有参与人  false 没有参与人
     *
     */
    public boolean calendarHasPart(String calendarId){
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT cs.id as id FROM oa_calendar oc  ");
        sql.append(" LEFT JOIN oa_calendar_scope cs on oc.participant = cs.fieldDataValue ");
        sql.append(" WHERE oc.id = :id ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id",  calendarId);
        List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap);
        if(CollectionUtils.isEmpty(list) || StringUtils.isBlank(StringUtils.null2String(list.get(0).get("id")))){//列表不为空或者首条数据为空
            return false;
        }else{
            return true;
        }
    }


    /**
     * 获取指定时间内拥有日程的日期
     * @param leaderWeekShow  展示方式  leaderWeekShow 领导日程周模式  myCalendar 个人日程周模式  shareCalendar 共享日程
     * @param leaderCateSelect  领导日程分类
     * @param userId  用户id
     * @param corpId  单位id
     * @param token  身份信息
     * @param startDate  查询开始时间
     * @param endDate  查询结束时间
     * @return OperationResult 结果集
     *
     *
     */
    public OperationResult getCalendarDates(String leaderWeekShow, String leaderCateSelect, String userId, String corpId, String token, String startDate, String endDate) throws ParseException {
        if(StringUtils.equals("leaderWeekShow",leaderWeekShow)) {//领导日程周模式
            Map<String, List<Map<String,String>>> leaderWeekMap = new HashMap<>();
            if(StringUtils.isNotBlank(leaderCateSelect)) {//选择了领导日程分类
                Map<String,String> leaderMap = calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(leaderCateSelect,userId,corpId,token,"");
                if(MapUtils.isNotEmpty(leaderMap)) {
                    Set<String> set = leaderMap.keySet();
                    StringBuilder leaderIds = new StringBuilder();
                    for (String leaderId : set) {
                        leaderIds.append(leaderId).append(",");
                    }
                    String leaderIdsStr = leaderIds.substring(0,leaderIds.length()-1);
                    List<Map<String, String>> dateList = this.getOaCalendarDate("", leaderIdsStr, corpId, "", startDate, endDate, token,"1");
                    leaderWeekMap.put("dateList", dateList);
                }
            }else {
                //用户可见的所有领导日程分类
                List<Map<String,String>> leaderCateList = calendarLeaderCategoryService.findCategoryInViewScope(userId, corpId);
                leaderWeekMap.put("leaderCateList", leaderCateList);
                if(CollectionUtils.isNotEmpty(leaderCateList)) {
                    //查询第一个领导日程分类下的所有领导
                    Map<String,String> leaderMap = calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(leaderCateList.get(0).get("id")+"",userId,corpId,token,"");
                    if(MapUtils.isNotEmpty(leaderMap)) {
                        Set<String> set = leaderMap.keySet();
                        StringBuilder leaderIds = new StringBuilder();
                        for (String leaderId : set) {
                            leaderIds.append(leaderId).append(",");
                        }
                        String leaderIdsStr = leaderIds.substring(0,leaderIds.length()-1);
                        List<Map<String, String>> dateList = this.getOaCalendarDate("", leaderIdsStr, corpId, "", startDate, endDate, token,"1");
                        leaderWeekMap.put("dateList", dateList);
                    }
                }
            }
            return OperationResult.buildSuccessResult(leaderWeekMap);
        }else if(StringUtils.equals("myCalendar",leaderWeekShow)){//个人日程周模式
            Map<String, List<Map<String,String>>> myCalendarAndcolumnValue = new HashMap<>();
            List<CalendarCategory> categories = calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
            List<Map<String, String>> maps = new ArrayList<>();
            if (categories != null && !categories.isEmpty()) {
                maps = this.getOaCalendarDate("", userId, corpId, "", startDate, endDate, token,"2");
            } else {
                maps = new ArrayList<Map<String, String>>();
            }
            myCalendarAndcolumnValue.put("myCalendar", maps);
            String columnValue = calendarSettingService.getCalendarColumn();
            List<Map<String, String>> columnValueList = new ArrayList<>();
            Map<String, String> columnValueMap = new HashMap<>();
            columnValueMap.put("columnValue", columnValue);
            columnValueList.add(columnValueMap);
            myCalendarAndcolumnValue.put("columnValueListMap", columnValueList);
            return OperationResult.buildSuccessResult(myCalendarAndcolumnValue);
        }else if(StringUtils.equals("shareCalendar",leaderWeekShow)){//共享日程
            List<Map<String, String>> maps = new ArrayList<>();
            maps = this.getOaCalendarDate("", userId, corpId, "share", startDate, endDate, token,"2");
            return OperationResult.buildSuccessResult(maps);
        }else {//选了两个或三个显示模块
            Map<String, List<Map<String,String>>> myAndLeaderWeekMap = new HashMap<>();
            String columnValue = calendarSettingService.getCalendarColumn();
            List<Map<String, String>> columnValueList = new ArrayList<>();
            Map<String, String> columnValueMap = new HashMap<>();
            columnValueMap.put("columnValue", columnValue);
            columnValueList.add(columnValueMap);
            myAndLeaderWeekMap.put("columnValueListMap", columnValueList);
            //用户可见的所有领导日程分类
            List<Map<String,String>> leaderCateList = calendarLeaderCategoryService.findCategoryInViewScope(userId, corpId);
            myAndLeaderWeekMap.put("leaderCateList", leaderCateList);
            if(CollectionUtils.isNotEmpty(leaderCateList)) {
                //查询第一个领导日程分类下的所有领导
                Map<String,String> leaderMap = calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(leaderCateList.get(0).get("id")+"",userId,corpId,token,"");
                if(MapUtils.isNotEmpty(leaderMap)) {
                    Set<String> set = leaderMap.keySet();
                    StringBuilder leaderIds = new StringBuilder();
                    for (String leaderId : set) {
                        leaderIds.append(leaderId).append(",");
                    }
                    String leaderIdsStr = leaderIds.substring(0,leaderIds.length()-1);
                    List<Map<String, String>> leaderDateList = this.getOaCalendarDate("", leaderIdsStr, corpId, "", startDate, endDate, token,"1");
                    myAndLeaderWeekMap.put("leaderDateList", leaderDateList);
                }
            }
            List<CalendarCategory> categories = this.calendarCategoryService.getCalendarCate("calendarSys", userId, corpId);
            List<Map<String, String>> myDateList = new ArrayList<>();
            if (categories != null && !categories.isEmpty()) {
                myDateList = this.getOaCalendarDate("", userId, corpId, "", startDate, endDate, token,"2");
            } else {
                myDateList = new ArrayList<Map<String, String>>();
            }
            myAndLeaderWeekMap.put("myDateList", myDateList);
            List<Map<String, String>> shareDateList = this.getOaCalendarDate("", userId, corpId, "share", startDate, endDate, token,"2");
            myAndLeaderWeekMap.put("shareDateList", shareDateList);
            return OperationResult.buildSuccessResult(myAndLeaderWeekMap);
        }
    }


    /**
     * 发送消息方法
     * @param request request请求
     * @param paramMapApp 参数map  包含内容参加调用
     * @param corpId 单位id
     * @param token 身份信息
     */
    public void sendMsg(HttpServletRequest request,Map<String,String> paramMapApp,String corpId,String token) {

        String remindStyle = paramMapApp.get("remindStyle");

        SendMessageDTO sendMessageDTO1 = new SendMessageDTO();
        sendMessageDTO1.setModuleCode("calendar");
        List<MessageBodyDTO> msgBodys1 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"umc","1");
        sendMessageDTO1.setMsgBodys(msgBodys1);
        List<String> msgTypes1 = new ArrayList<String>();
        msgTypes1.add("umc");
        if(StringUtils.isNotEmpty(remindStyle) && remindStyle.contains("sms")){//提醒方式包含短信
            msgTypes1.add("sms");
        }
        sendMessageDTO1.setMsgTypes(msgTypes1);
        sendMessageDTO1.setCorpId(corpId);
        sendMessageDTO1.setToken(token);
        sendMessageDTO1.setResourceType(ResourceTypes.SYSTEM.getCode());
        sendMessageApiService.sendMessage(sendMessageDTO1);

        if(StringUtils.isNotBlank(remindStyle) && remindStyle.contains("mobile")){//提醒方式包含移动端
            SendMessageDTO sendMessageDTO2 = new SendMessageDTO();
            sendMessageDTO2.setModuleCode("calendar");
            List<MessageBodyDTO> msgBodys2 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"mobile","1");
            sendMessageDTO2.setMsgBodys(msgBodys2);
            List<String> msgTypes2 = new ArrayList<String>();
            msgTypes2.add("mobile");
            sendMessageDTO2.setMsgTypes(msgTypes2);
            sendMessageDTO2.setCorpId(corpId);
            sendMessageDTO2.setToken(token);
            LOG.error("日程移动端消息："+JSON.toJSONString(sendMessageDTO2));
            sendMessageDTO2.setResourceType(ResourceTypes.SYSTEM.getCode());
            sendMessageApiService.sendMessage(sendMessageDTO2);
        }

        if(StringUtils.isNotBlank(remindStyle) && remindStyle.contains("mail")){//提醒方式包含邮件
            LOG.debug("进来了");
            String message = this.sendMailMsg(corpId,token,paramMapApp);
            LOG.debug("错误信息："+message);
        }

    }

    /**
     * 根据参数名获取系统设置值
     * @param corpId
     * @param token
     * @return
     */
    public String sendMailMsg(String corpId, String token, Map<String,String> paramMapApp) {
        RestClient restClient = new RestClient(false);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("isOpenMobile", "0");
        paramMap.put("isOpenSms", "0");
        paramMap.put("mailSecretLevel", "4");
        String userJsonStr = this.getSendUser(paramMapApp);
//        paramMap.put("mailRecipients", userJsonStr);
        paramMap.put("mailTheme", paramMapApp.get("title"));
        String mailText = this.getMailMsg(paramMapApp,corpId,token);
        paramMap.put("mailText", mailText);
        paramMap.put("mailStatus", "1");
        paramMap.put("saveToFolderId", "1");
        paramMap.put("draft", "1");
        paramMap.put("savePwdInSent", "0");
        paramMap.put("mailType", "0");
        paramMap.put("sendSecretStatus", "false");
        paramMap.put("sendCopyStatus", "false");
        paramMap.put("forwardType", "calendar");

        String jwtToken = this.getTempBaseAccessToken(GlobalConstant.getConfig("app.flexbase.server.url"),GlobalConstant.getConfig("app.flexbase.client_id"),GlobalConstant.getConfig("app.flexbase.client_secret"),"/oauth2/token");

        String userInfoStr= AuthUtils.getUserAuth2(paramMapApp.get("userId"), corpId, "0",jwtToken,null);
        if(userInfoStr.equals("-1")) {//查询用户登录失败
            LOG.error("登录失败,没有登录权限!");
        }else {
            JSONObject jsonobj1 = new JSONObject();
            jsonobj1 = JSONObject.parseObject(userInfoStr);
            if(jsonobj1.getString("code").equals("0")) {
                JSONObject userJson = jsonobj1.getJSONObject("data");
                token = userJson.getString("token");
            }else {
                LOG.error("登录失败,没有登录权限!");
            }
        }
        //String jsonStr = restClient.post("/w/mail/mailbasics/saveMail", token, paramMap, userJsonStr);
        String jsonStr = mailApiService.saveMail(token, paramMap, userJsonStr);
        Map<String, Object> result = JsonUtils.readValue(jsonStr);
        if (result != null && result.size()>0) {
            if ("success".equals(result.get("type"))) {
                return String.valueOf(result.get("data"));
            }
        }
        return "";
    }

    /**
     * 该token仅生效一次
     * @param baseUrl
     * @param clientId
     * @param clientSecret
     * @param tokenUrl
     * @return
     * @throws Exception
     */
    public String getTempBaseAccessToken(String baseUrl,String clientId,String clientSecret,String tokenUrl) {
        try {
            String tempBaseAccessToken = "";
            AccessToken acctessToken = null;
            Client client = new Client();
            Map<String, String> params = new HashMap<String, String>();
            params.put("client_id", clientId);
            params.put("client_secret", clientSecret);
            params.put("grant_type", "client_credentials");

            acctessToken = client.getToken(baseUrl + tokenUrl, params);
            if(acctessToken!=null) {
                tempBaseAccessToken = acctessToken.getAccessToken();
            }
            return tempBaseAccessToken;
        }catch(Exception e) {
            LOG.error("获取token错误",e);
            return "";
        }
    }

    /**
     * 获取邮件发送人scope值
     *
     */
    public String getSendUser(Map<String,String> paramMapApp){
        List<Map<String, Object>> sendUserList = popUserScopeUtilService.getScopeJsonDataList("oa_calendar_scope",paramMapApp.get("participant"),"oa_calendar","participant");
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("scopeType","user");
        userMap.put("scopeName",paramMapApp.get("name"));
        userMap.put("scopeValue",paramMapApp.get("userId"));
        sendUserList.add(userMap);

        String userJsonStr = JSON.toJSONString(sendUserList);

        return userJsonStr;
    }

    /**
     * 拼装邮件内容
     * @param paramMapApp 日程的参数map
     * @param corpId 单位id
     * @param token 身份信息
     * @return  String 要发送的邮件体
     *
     *
     */
    public String getMailMsg(Map<String,String> paramMapApp,String corpId, String token){

        String partNames = "";
        List<Map<String,Object>> userInfoList = userApiService.getUserList(paramMapApp.get("ids"),corpId,"",token);
        if(CollectionUtils.isNotEmpty(userInfoList)){
            for(Map<String,Object> userMap : userInfoList){
                partNames += userMap.get("userName") + ",";
            }
            partNames = partNames.substring(0,partNames.length()-1);
        }


        String mailText = "<div> " +
                "<div>日程提醒：</div><br/>" +
                "<div>您有个日程即将开始，请及时处理！</div><br/> " +
                "<table cellspacing='1' cellpadding='0' class='ueditor-insert-table'> " +
                "<tbody> " +
                "<tr class='firstRow'> " +
                "<th style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>日期</th> " +
                "<th style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>开始时间</th> " +
                "<th style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>结束时间</th> " +
                "<th style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>日程标题</th> " +
                "<th style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>参与人</th>" +
                "</tr>" +
                "<tr>" +
                "<td style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>"+paramMapApp.get("startDate")+"</td> " +
                "<td style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>"+paramMapApp.get("startTime")+"</td> " +
                "<td style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>"+paramMapApp.get("endTime")+"</td> " +
                "<td style='border: 1px solid rgb(221, 221, 221); word-break: break-all; color:red;' width='240' valign='top' " +
                " class='cursor-pointer' onclick=\"viewCalendar('"+paramMapApp.get("dataId")+"'" +
                ",'"+paramMapApp.get("repeat")+"','"+paramMapApp.get("start")+"','"+paramMapApp.get("end")+"'" +
                ",'"+paramMapApp.get("userId")+"','"+paramMapApp.get("belongCalendar")+"','"+paramMapApp.get("isMaintain")+"')\">"+paramMapApp.get("title")+"</td> " +
                "<td style='border: 1px solid rgb(221, 221, 221); word-break: break-all;' width='240' valign='top'>"+partNames+"</td> " +
                "</tr> " +
                "</tbody> " +
                "</table> " +
                "<input type='hidden' data-module='calendar' />" +
                "<input type='hidden' id='secdatacodeVal' />" +
                "</div>";

        return mailText;

    }



    /**
     * 获取日程数据
     * @param viewType 查看方式 share 领导、共享  ；其他 我的
     * @param userName 当前登录人姓名
     * @param leaderOrSub 领导嚯下属日程 1 是
     * @param categoryId 日程分类Id
     * @param userId 当前用户登录id
     * @param corpId 单位Id
     * @param token 身份信息
     * @param orgId 组织id
     * @param currentDate 查询时间
     * @param userIdPhone 移动端传过来的用户id
     * @param logCode 日志类型  用于区分是什么日程
     *
     *
     *
     */
    public Map<String, Object> getDateCalendarResult(String viewType, String userName, String leaderOrSub, String categoryId, String userId, String corpId,
                                                     String token, String orgId,  String currentDate, String userIdPhone, String logCode){

        String sharedId = "";//共享人id

        String userLocal = userId;

        List<Map<String, String>> shareList = new ArrayList<>();//
        if("share".equals(viewType)){
            shareList = this.getShareOwner(userId, corpId, token);//获取共享给我日程的人列表
            sharedId = userIdPhone;
        }

        Map<String, Object> content = new HashMap<>();
        content.put("userName", userName);

        List<Map<String, String>> events = new ArrayList<>();
        Map<String,List<Map<String, String>>> maps = new HashMap();
        boolean shareFlag = false;//共享日程标识

        Map<String, String> canEditLeaders = new HashMap<String, String>();
        if (StringUtils.equals("1", leaderOrSub)) {
            if(StringUtils.isNotEmpty(categoryId) && !"null".equals(categoryId)) {//领导日程
                Map<String,String> leaderMap = this.calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(categoryId,userId,corpId,token,orgId);
                StringBuffer sb = new StringBuffer();
                if(MapUtils.isNotEmpty(leaderMap)) {
                    for(String leaderId : leaderMap.keySet()) {
                        sb.append(leaderId + ",");
                    }
                    userId = sb.toString().substring(0,sb.toString().length()-1);
                }else {
                    userId = "";
                }
                canEditLeaders = this.calendarLeaderSettingService.getLeaderIdsByUserIdAndCategoryId("", userLocal,"",corpId, categoryId, token);
            }else {
                userId = userIdPhone;
            }
        }
        if("share".equals(viewType)) {
            shareFlag = true;
            if(CollectionUtils.isNotEmpty(shareList)) {
                for(Map<String,String> map : shareList) {
                    List<Map<String, String>> event = this.getAllOaCalendar(userId, map.get("userId"), viewType, corpId, currentDate,"", token, -1,"phone","2");
                    if(CollectionUtils.isNotEmpty(event)) {
                        maps.put(map.get("name"), new ArrayList<Map<String, String>>());
                        for(Map<String, String> eventMap : event) {
                            maps.get(map.get("name")).add(eventMap);
                        }
                    }
                }
            }
        }else {
            events = this.getAllOaCalendar(userId, sharedId, viewType, corpId, currentDate,"", token, -1,"phone",leaderOrSub);

        }

        if("leader".equals(logCode)){
            events = this.changePartToLeaderName(events, userId, corpId, token,"");
        }

        //获取人名-日程分类组织树
        if(CollectionUtils.isNotEmpty(events)) {
            if(!shareFlag) {
                if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {//领导日程不需要分类
                    List<Map<String, String>> leaderList = new ArrayList<Map<String, String>>();
                    for(Map<String, String> map :events) {
                        String calendarOwner = map.get("calendarOwner");
                        String leader = map.get("leader");
                        if(canEditLeaders != null) {
                            if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(calendarOwner)))) {
                                map.put("canEdit", "yes");
                            }else {
                                map.put("canEdit", "no");
                            }
                            if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(leader)))){
                                map.put("canComplete", "yes");
                            }

                        }else {
                            map.put("canEdit", "no");
                        }
                        leaderList.add(map);
                    }
                    maps.put("leaderCate", leaderList);
                }else {
                    for(Map<String, String> map :events) {
                        String category = map.get("category");
                        maps.put(category, new ArrayList<Map<String, String>>());
                    }
                    for(Map<String, String> map :events) {
                        String category = map.get("category");
                        maps.get(category).add(map);
                    }
                }
            }
        }
        List list = new ArrayList();
        for (Map.Entry<String,List<Map<String, String>>> entry : maps.entrySet()) {
            Map<String,Object> allDayEvents = new HashMap();
            allDayEvents.put("cate", entry.getKey());
            allDayEvents.put("calendars", entry.getValue());
            list.add(allDayEvents);
        }
        content.put("allDayEvents", list);
        content.put("events", events);

        return content;
    }


    /**
     * 获取指定时间内拥有日程的日期和当前日期的日程
     * @param userId 登录人Id
     * @param corpId 单位id
     * @param token 身份信息
     * @param userPhoneId 移动端获取的用户id
     * @param viewType 查看类型
     * @param currentDate 当前时间
     * @param userName 登录人姓名
     * @param leaderOrSub 领导或者下属 1 是 0 否
     * @param orgId 组织id
     * @param categoryId 分类id
     * @param  logCode 日程日志编码（确定选择的日程）
     * @return result Map<String, Object> 结果集
     *
     *
     */
    public Map<String, Object> showMonthViewResult(String userId, String corpId, String token, String userPhoneId, String viewType, String currentDate, String userName,
                                    String leaderOrSub, String orgId, String categoryId, String logCode) throws ParseException {

        String localUserId = userId;
        String sharedId = "";
        List<Map<String, String>> shareList = new ArrayList<>();
        if("share".equals(viewType)){
            //查询所有共享用户
            shareList = this.getShareOwner(userId, corpId, token);
            sharedId = userPhoneId;
        }
        String[] ymd = currentDate.split("-");
        String start = CalendarUtils.getFirstDayOfMonth(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]));
        String end = CalendarUtils.getLastDayOfMonth(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]));

        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("success", true);
        result.put("message", "成功");
        Map<String, Object> content = new HashMap<>();
        content.put("userName", userName);
        List<Map<String, String>> dates = new ArrayList<>();

        Map<String, String> canEditLeaders = new HashMap<String, String>();
        if (StringUtils.equals("1", leaderOrSub)) {
            if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {//领导日程
                Map<String,String> leaderMap = this.calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(categoryId,userId,corpId,token,orgId);
                StringBuffer sb = new StringBuffer();
                if(MapUtils.isNotEmpty(leaderMap)) {
                    for(String leaderId : leaderMap.keySet()) {
                        sb.append(leaderId + ",");
                    }
                    userId = sb.toString().substring(0,sb.toString().length()-1);
                }else {
                    userId = "";
                }
                canEditLeaders = this.calendarLeaderSettingService.getLeaderIdsByUserIdAndCategoryId("", localUserId,"", corpId, categoryId, token);
            }else {
                userId = userPhoneId;
            }
        }
        if("share".equals(viewType)) {
            //查询所有共享用户
            if(CollectionUtils.isNotEmpty(shareList)) {
                for(Map<String,String> map : shareList) {
                    List<Map<String, String>> date = this.getOaCalendarDate(map.get("userId"), userId, corpId, viewType, start, end, token,leaderOrSub);
                    dates.addAll(date);
                }
            }
        }else {
            dates = this.getOaCalendarDate(sharedId, userId, corpId, viewType, start, end, token,leaderOrSub);
        }
        content.put("dates", dates);
        Map<String,List<Map<String, String>>> maps = new HashMap();
        List<Map<String, String>> events = new ArrayList<>();
        boolean shareFlag = false;//共享日程标识
        if("share".equals(viewType)) {
            shareFlag = true;
            if(CollectionUtils.isNotEmpty(shareList)) {
                for(Map<String,String> map : shareList) {
                    List<Map<String, String>> event = this.getAllOaCalendar(userId, map.get("userId"), viewType, corpId, currentDate,"", token, -1,"phone","2");
                    if(CollectionUtils.isNotEmpty(event)) {
                        maps.put(map.get("name"), new ArrayList<Map<String, String>>());
                        for(Map<String, String> eventMap :event) {
                            maps.get(map.get("name")).add(eventMap);
                        }
                    }
                }
            }
        }else {
            events = this.getAllOaCalendar(userId, sharedId, viewType, corpId, currentDate,"", token, -1,"phone",leaderOrSub);
        }

        if("leader".equals(logCode)){
            events = this.changePartToLeaderName(events, userId, corpId, token,"");
        }

        //获取类别-日程分类组织树
        if(CollectionUtils.isNotEmpty(events)) {
            if(!shareFlag) {
                if(StringUtils.isNotEmpty(orgId) &&  !"null".equals(orgId)) {//领导日程不需要分类
                    List<Map<String, String>> leaderList = new ArrayList<Map<String, String>>();
                    for(Map<String, String> map :events) {
                        String calendarOwner = map.get("calendarOwner");
                        String leader = map.get("leader");
                        if(canEditLeaders != null) {
                            if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(calendarOwner)))) {
                                map.put("canEdit", "yes");
                            }else {
                                map.put("canEdit", "no");
                            }

                            if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(leader)))){
                                map.put("canComplete", "yes");
                            }

                        }else {
                            map.put("canEdit", "no");
                        }
                        leaderList.add(map);
                    }
                    maps.put("leaderCate", leaderList);
                }else {
                    for(Map<String, String> map :events) {
                        String category = map.get("category");
                        maps.put(category, new ArrayList<Map<String, String>>());
                    }
                    for(Map<String, String> map :events) {
                        String calendarOwner = map.get("calendarOwner");
                        if(canEditLeaders != null) {
                            if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(calendarOwner)))) {
                                map.put("canEdit", "yes");
                            }else {
                                map.put("canEdit", "no");
                            }
                        }else {
                            map.put("canEdit", "no");
                        }
                        String category = map.get("category");
                        maps.get(category).add(map);
                    }
                }
            }
        }
        List list = new ArrayList();
        for (Map.Entry<String,List<Map<String, String>>> entry : maps.entrySet()) {
            Map<String,Object> allDayEvents = new HashMap();
            allDayEvents.put("cate", entry.getKey());
            allDayEvents.put("calendars", entry.getValue());
            list.add(allDayEvents);
        }
        content.put("allDayEvents", list);
        content.put("events", events);
        result.put("content", content);

        return result;
    }

    /**
     * 获取当前整个月的日程
     * @param viewType 视图类型 share 下属、领导  mine
     * @param userName 登录人中文名
     * @param userIdPhone 移动端过来的用户id
     * @param pageable 分页参数
     * @param leaderOrSub 是否是领导或者下属 1 是 0 否
     * @param orgId 组织id
     * @param userId 登录人用户id
     * @param corpId 单位id
     * @param token 身份信息
     * @param categoryId 日程分类id
     * @param  logCode 日程日志编码（用来区分选择的日程）
     *
     * @return result Map<String, Object> 结果集
     *
     */
    public Map<String, Object> showListViewResult(String viewType, String userName, String userIdPhone, Pageable pageable, String leaderOrSub, String orgId, String userId,
                                   String corpId, String token, String categoryId, String logCode){
        String category = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String localUserId = userId;

        String sharedId = "";
        if("share".equals(viewType)){
            sharedId = userIdPhone;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("success", true);
        result.put("message", "成功");
        Map<String, Object> content = new HashMap<>();
        content.put("userName", userName);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, String>> calendarList = new ArrayList<>();
        String year = CalendarUtils.getStrByDate(new Date(), "yyyy");
        String month = CalendarUtils.getStrByDate(new Date(), "MM");
        String yearMonth =  CalendarUtils.getStrByDate(new Date(), "yyyy-MM");
        int day = CalendarUtils.getMonthMaxDay(Integer.parseInt(year), Integer.parseInt(month)-1);
        Object[] object = new Object[day+1];
        String start = yearMonth+"-01";
        String end = yearMonth+"-"+day;
        String[] dates = CalendarUtils.getMonthInTwoDate(start, end);

        String shareId = "";

        boolean shareFlag = false;//共享日程标识
        Map<String, String> canEditLeaders = new HashMap<String, String>();
        if (StringUtils.equals("1", leaderOrSub)) {
            if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {//领导日程
                Map<String,String> leaderMap = this.calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(categoryId,userId,corpId,token,orgId);
                StringBuffer sb = new StringBuffer();
                if(MapUtils.isNotEmpty(leaderMap)) {
                    for(String leaderId : leaderMap.keySet()) {
                        sb.append(leaderId + ",");
                    }
                    shareId = sb.toString().substring(0,sb.toString().length()-1);
                }else {
                    shareId = "";
                }
                //可维护的领导集合
                canEditLeaders = this.calendarLeaderSettingService.getLeaderIdsByUserIdAndCategoryId("", localUserId, "", corpId, categoryId, token);
            }else {
                shareId = userIdPhone;
            }
            calendarList = this.getOaCalendarAll(pageable, "", category, shareId, corpId, "", viewType, dates[0], dates[1], token, leaderOrSub);
        }else{
            if("share".equals(viewType)) {
                shareFlag = true;
                List<Map<String, String>> shareList = this.getShareOwner(userId, corpId, token);
                if(CollectionUtils.isNotEmpty(shareList)) {
                    for(Map<String,String> map : shareList) {
                        List<Map<String, String>> calendarListOne = this.getOaCalendarAll(pageable, map.get("userId"), category, userId, corpId, "", viewType, dates[0], dates[1], token, "0");
                        if(CollectionUtils.isNotEmpty(calendarListOne)) {
                            for(Map<String,String> eventMap : calendarListOne) {
                                eventMap.put("userName", map.get("name"));
                            }
                        }
                        calendarList.addAll(calendarListOne);
                    }
                }
            }else {
                calendarList = this.getOaCalendarAll(pageable, sharedId, category, userId, corpId, "", viewType, dates[0], dates[1], token, "0");
            }
        }

        if("leader".equals(logCode)){
            calendarList = this.changePartToLeaderName(calendarList, shareId, corpId, token,"");
        }


        if(calendarList!=null && !calendarList.isEmpty()) {
            for(int i=0;i<calendarList.size();i++) {
                List<Map<String, String>> newCalendar = new ArrayList<>();
                String time = calendarList.get(i).get("start").substring(8, 10);
                String calendarOwner = calendarList.get(i).get("calendarOwner");
                String leader = calendarList.get(i).get("leader");
                if(canEditLeaders != null) {
                    if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(calendarOwner)))) {
                        calendarList.get(i).put("canEdit", "yes");
                    }else {
                        calendarList.get(i).put("canEdit", "no");
                    }

                    if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(leader)))){
                        calendarList.get(i).put("canComplete", "yes");
                    }

                }else {
                    calendarList.get(i).put("canEdit", "no");
                }
                Integer num = Integer.parseInt(time);
                if(object[num] == null) {
                    newCalendar.add(calendarList.get(i));
                    object[num] = newCalendar;
                }else {
                    newCalendar = (List<Map<String, String>>) object[num];
                    newCalendar.add(calendarList.get(i));
                    object[num] = newCalendar;
                }
            }
            for (int i = 0;i<object.length;i++) {
                List<Map<String, String>> newCalendar = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                if(object[i] != null) {
                    newCalendar = (List<Map<String, String>>) object[i];
                    map.put("date", newCalendar.get(0).get("startDate"));
                    map.put("events",newCalendar);
                    list.add(map);
                }
            }
        }
        content.put("datas", list);
        //处理list按 日期-日程分类-分类下日程三层结构;
        for(Map<String,Object> map : list) {
            Map<String,List<Map<String, String>>> maps = new HashMap();
            List<Map> lists = (List)map.get("events");
            if(CollectionUtils.isNotEmpty(lists)) {
                if(shareFlag) {
                    for(Map<String, String> sigleDayCalendar :lists) {
                        String category1 = sigleDayCalendar.get("userName").toString();
                        maps.put(category1, new ArrayList<Map<String, String>>());
                    }
                    for(Map<String, String> map1 :lists) {
                        String category2 = map1.get("userName");
                        maps.get(category2).add(map1);
                    }
                }else {
                    if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {
//                        for(Map<String, String> sigleDayCalendar :lists) {
//                            String category1 = "leaderCalendar";
//                            maps.put(category1, new ArrayList<Map<String, String>>());
//                        }
                        if(CollectionUtils.isNotEmpty(lists)){
                            List<Map<String,String>> dataList = new ArrayList<Map<String, String>>();
                            String category1 = "leaderCalendar";
                            for(Map<String, String> map1 :lists) {
                                dataList.add(map1);
                            }
                            maps.put(category1, dataList);
                        }

                    }else {
                        for(Map<String, String> sigleDayCalendar :lists) {
                            String category1 = sigleDayCalendar.get("category").toString();
                            maps.put(category1, new ArrayList<Map<String, String>>());
                        }
                        for(Map<String, String> map1 :lists) {
                            String category2 = map1.get("category");
                            maps.get(category2).add(map1);
                        }
                    }
                }
            }
            List list1 = new ArrayList();
            for (Map.Entry<String,List<Map<String, String>>> entry : maps.entrySet()) {
                List<Map<String, String>> sortList = entry.getValue();
                Collections.sort(sortList, new Comparator<Map<String, String>>() {
                    @Override
                    public int compare(Map<String, String> o1, Map<String, String> o2) {
                        Date date1 = null;
                        Date date2 = null;
                        try {
                            date1 = format.parse(StringUtils.equals(o1.get("isAllDay"), "1")?o1.get("start")+" 00:00":o1.get("start"));
                            date2 = format.parse(StringUtils.equals(o2.get("isAllDay"), "1")?o2.get("start")+" 00:00":o2.get("start"));
                        }catch (ParseException e) {
                            LOG.error("时间转换出错",e);
                        }
                        return date1.compareTo(date2);
                    }
                });
                LinkedHashMap<String,Object> allDayEvents = new LinkedHashMap<String, Object>();
                allDayEvents.put("cate", entry.getKey());
                allDayEvents.put("calendars", sortList);
                list1.add(allDayEvents);
            }
            map.put("allDayEvent", list1);
        }
        result.put("content", content);

        return result;
    }

    /**
     * 将选人的字符串转换为List
     * @param scopeValue 选人字符串
     * @param type 查看类型  eidt 编辑  其他
     * @param token 身份信息
     * @param corpId 单位id
     * @return userScope
     */
    public String transformUserScopeByDd1(String scopeValue,String type,String token, String corpId ){
        Map<String,String> csIdsMap = new HashMap<>();
        String userScope = "";
        int editLength=0 ;
        if(StringUtils.isNotBlank(scopeValue)){
            String[] scopeCs = scopeValue.split(",");
            String csUserId = "";
            String n = "";
            //编辑不显示被删除人
            if(StringUtils.equals("eidt", type)) {
                for(String cs : scopeCs){
                    csUserId = cs.split("SCOPE")[1];
                    if(StringUtils.equals("user", cs.split("SCOPE")[0])) {
                        List<Map> list= this.findUserName(csUserId);
                        if(CollectionUtils.isNotEmpty(list)) {
                            n = list.get(0).get("user_name").toString();
                            if(StringUtils.equals("0", list.get(0).get("is_delete").toString())) {
                                csIdsMap.put(csUserId,cs.split("SCOPE")[0]+";"+n);
                                editLength++;
                            }
                        }
                    }else {
                        n = userApiService.getScopeName(cs,corpId,token);
                        csIdsMap.put(csUserId,cs.split("SCOPE")[0]+";"+n);
                        editLength++;
                    }
                }
            }else {
                for(String cs : scopeCs){
                    csUserId = cs.split("SCOPE")[1];
                    if(StringUtils.equals("user", cs.split("SCOPE")[0])) {
                        List<Map> list= this.findUserName(csUserId);
                        if(CollectionUtils.isNotEmpty(list)) {
                            n = list.get(0).get("user_name").toString();
                        }
                        csIdsMap.put(csUserId,cs.split("SCOPE")[0]+";"+n);
                    }else {
                        n = userApiService.getScopeName(cs,corpId,token);
                        csIdsMap.put(csUserId,cs.split("SCOPE")[0]+";"+n);
                    }
                }
            }
        }
        if(StringUtils.isNotBlank(scopeValue)){
            for (Map.Entry<String, String> entry : csIdsMap.entrySet()) {
                String[] scopeList = entry.getValue().split(";");
                if("".equals(userScope)) {
                    userScope = "[{\"scopeType\":\""+scopeList[0]+"\",\"scopeValue\":\""+entry.getKey()+"\",\"scopeName\":\""+scopeList[1]+"\"}";
                }else {
                    userScope +=",{\"scopeType\":\""+scopeList[0]+"\",\"scopeValue\":\""+entry.getKey()+"\",\"scopeName\":\""+scopeList[1]+"\"}";
                }
            }
            if(StringUtils.equals("eidt", type)) {
                if(editLength!=0) {
                    userScope+="]";
                }
            }else {
                userScope+="]";
            }
        }
        return userScope;
    }


    /**
     * 将选人的字符串转换为List
     * @param scopeValue 选人字符串
     * @param type 查看类型  eidt 编辑  其他
     * @param token 身份信息
     * @param corpId 单位id
     * @return userScope
     */
    public String transformUserScopeByDd(String scopeValue,String type,String token, String corpId ){
        String userScope = "";
        String scopeName = "";
        if(StringUtils.isNotBlank(scopeValue)){
            scopeName = userApiService.getScopeName(scopeValue,corpId,token);
        }
        if(StringUtils.isNotBlank(scopeName)){
            String[] scopeNameArr = scopeName.split(",");
            String[] scopeArr = scopeValue.split(",");
            for(int i=0; i<scopeArr.length; i++){
                String[] scopeItemArr = scopeArr[i].split("SCOPE");
                if(StringUtils.isEmpty(userScope)){
                    userScope = "[{\"scopeType\":\""+scopeItemArr[0]+"\",\"scopeValue\":\""+scopeItemArr[1]+"\",\"scopeName\":\""+scopeNameArr[i]+"\"}";
                }else{
                    userScope += ",{\"scopeType\":\""+scopeItemArr[0]+"\",\"scopeValue\":\""+scopeItemArr[1]+"\",\"scopeName\":\""+scopeNameArr[i]+"\"}";
                }
            }
            userScope+="]";
        }
        return userScope;
    }

    /**
     * 移动端保存日程
     * @param request 接口请求
     * @param userId 登录人id
     * @param corpId 单位id
     * @param token 身份信息
     * @return Map<String, Object> resultMap 结果信息集
     *
     */
    public Map<String, Object> saveCalendarForMobile(HttpServletRequest request, String userId, String corpId, String token){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        Map<String, String> paramsMap = null;

        Date startNow = new Date();
        Date endNow = new Date();

        String requestParams = request.getParameter("calendar");

        try {
            boolean isAdd = false;
            //解析参数
            paramsMap = (Map) mapper.readValue(requestParams, Map.class);//解析的参数map
            String type = StringUtils.null2String(paramsMap.get("updateType"));//"current"-编辑当前日程，"all"-编辑全部日程 针对重复日程
            String weekSelectValue = StringUtils.null2String(paramsMap.get("weekSelectValue"));//重复日程参数 周
            String monthSelectValue = StringUtils.null2String(paramsMap.get("monthSelectValue"));// 重复日程参数 月
            String monthRadioValue = StringUtils.null2String(paramsMap.get("monthRadioValue"));// 重复日程参数 选择

            Calendar calendar = new Calendar();
            if(paramsMap != null){
                String id = StringUtils.null2String(paramsMap.get("id"));//日程Id 新增为空 重复日程子日程为空

                String logCodeType = StringUtils.null2String(paramsMap.get("logCode"));
                //获取新的分类id
                String newCalendarCateId = UuidUtils.UUID();
                String oldCalendarCateId = StringUtils.null2String(paramsMap.get("calendarCategory"));//分类id

                //保存前 处理下系统初始化的两个日程分类(calendarSysWork,calendarSysPerson)
                CalendarCategory calendarSysCategory = calendarCategoryDao.getCategoryById(oldCalendarCateId,"0");
                //日程分类所属人
                String cateOwer = "";
                if(StringUtils.equals(logCodeType, "calendar")) {
                    cateOwer = userId;
                }else {
                    cateOwer = StringUtils.null2String(paramsMap.get("sharedId"));
                }

                /** 日程分类处理开始 **/
                //如果是工作系统日程
                if(StringUtils.equals("calendarSysWork", calendarSysCategory.getCode())) {
                    //需要重新设置id,createdBy,code
                    CalendarCategory ca = new CalendarCategory();
                    ca.setId(newCalendarCateId);
                    ca.setCreatedBy(cateOwer);
                    ca.setCode("singleWork");
                    ca.setBackColor(calendarSysCategory.getBackColor());
                    ca.setCategory(calendarSysCategory.getCategory());
                    ca.setCorpId(calendarSysCategory.getCorpId());
                    ca.setCreator(calendarSysCategory.getCreator());
                    ca.setMaintainer(calendarSysCategory.getMaintainer());
                    ca.setName(calendarSysCategory.getName());
                    ca.setSortNo(calendarSysCategory.getSortNo());
                    ca.setSource(calendarSysCategory.getSource());
                    ca.setViewer(calendarSysCategory.getViewer());
                    paramsMap.put("calendarCategory",ca.getId());
                    //保存类别
                    this.calendarCategoryService.save(ca);
                }
                //如果是个人系统日程
                if(StringUtils.equals("calendarSysPerson", calendarSysCategory.getCode())) {
                    //需要重新设置id,createdBy,code
                    CalendarCategory ca = new CalendarCategory();
                    ca.setId(newCalendarCateId);
                    ca.setCreatedBy(cateOwer);
                    ca.setCode("singlePerson");
                    ca.setBackColor(calendarSysCategory.getBackColor());
                    ca.setCategory(calendarSysCategory.getCategory());
                    ca.setCorpId(calendarSysCategory.getCorpId());
                    ca.setCreator(calendarSysCategory.getCreator());
                    ca.setMaintainer(calendarSysCategory.getMaintainer());
                    ca.setName(calendarSysCategory.getName());
                    ca.setSortNo(calendarSysCategory.getSortNo());
                    ca.setSource(calendarSysCategory.getSource());
                    ca.setViewer(calendarSysCategory.getViewer());
                    paramsMap.put("calendarCategory",ca.getId());
                    //保存类别
                    this.calendarCategoryService.save(ca);
                }
                /** 日程分类处理结束 **/

                //日志编码处理
                String logCode = "";
                if(StringUtils.equals(logCodeType, "calendar")) {
                    logCode = "calendar:mycalendar";
                }else if(StringUtils.equals(logCodeType, "leader")) {
                    logCode = "calendar:leader";
                }

                // 日程数据处理  新增、修改
                if(!"".equals(id)){//编辑

                    calendar = this.findOne(id);
                    //日志记录
                    logCode = logCode + ":02";
                    boolean logSet = this.logService.checkOptLog(corpId, logCode, token);
                    if(logSet){
                        logService.saveModuleLog(logCode, calendar.getTitle(), "");
                    }
                }else {//新增
                    //日志记录
                    logCode = logCode + ":01";
                    boolean logSet = this.logService.checkOptLog(corpId, logCode, token);
                    if(logSet){
                        logService.saveModuleLog(logCode, paramsMap.get("title"), "");
                    }
                }

                if(!"".equals(id)){
                    if(!"current".equals(type)){//重复日程子日程
                        startNow = calendar.getStartDate();
                        endNow = calendar.getEndDate();
                    }
                }

                String isAllDay = paramsMap.get("isAllDay");
                calendar.setIsAllDay(isAllDay);
                String start = paramsMap.get("startTime");
                Date date1 = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
                calendar.setStartDate(date1);
                if("1".equals(isAllDay)){
                    calendar.setStartTime(0);
                    calendar.setEndTime(0);
                    calendar.setEndDate(null);
                }else{
                    int seconds = CalendarUtils.getSecondsByStrDate(start);
                    calendar.setStartTime(seconds);
                    String end = paramsMap.get("endTime");
                    Date date2 = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");
                    calendar.setEndDate(date2);
                    seconds = CalendarUtils.getSecondsByStrDate(end);
                    calendar.setEndTime(seconds);
                }
                calendar.setTitle(paramsMap.get("title"));
                calendar.setCalendarCategory(paramsMap.get("calendarCategory"));
                calendar.setContent(paramsMap.get("content"));
                calendar.setAddress(paramsMap.get("address"));
                calendar.setIsMain(paramsMap.get("isMain"));
                calendar.setCalendarOwner(paramsMap.get("calendarOwner"));
                calendar.setBelongCalendar(paramsMap.get("belongCalendar"));
                calendar.setDuplicateType(paramsMap.get("duplicateType"));
                calendar.setDuplicateInterval(paramsMap.get("duplicateInterval"));
                calendar.setDuplicateEndType(paramsMap.get("duplicateEndType"));
                calendar.setDuplicateEndTypeValue(paramsMap.get("duplicateEndTypeValue"));
                calendar.setExpiryReminder(paramsMap.get("expiryReminder"));
                calendar.setExpiryReminderTime(paramsMap.get("expiryReminderTime"));
                calendar.setRemindStyle(paramsMap.get("remindStyle"));
                calendar.setParticipant(paramsMap.get("participant"));
                calendar.setViewer(paramsMap.get("viewer"));
                calendar.setMaintainer(paramsMap.get("maintainer"));
                String noEditAttachment = StringUtils.null2String(paramsMap.get("noEditAttachment"));
                calendar.setAttachment(noEditAttachment + StringUtils.null2String(paramsMap.get("imgIds")));
                calendar.setDegreeOfImportance(paramsMap.get("degreeOfImportance"));
                calendar.setCreatedDate(new Date());
                if(StringUtils.equals("week", StringUtils.null2String(calendar.getDuplicateType()))) {
                    calendar.setWeekMonthDuplicateType(weekSelectValue);
                }
                if(StringUtils.equals("month", StringUtils.null2String(calendar.getDuplicateType()))) {
                    calendar.setWeekMonthDuplicateType(monthSelectValue+monthRadioValue);
                }
                String part = StringUtils.null2String(paramsMap.get("participant"));
                String viewer = StringUtils.null2String(paramsMap.get("viewer"));
                String maintainer = StringUtils.null2String(paramsMap.get("maintainer"));
                String viewType = StringUtils.null2String(paramsMap.get("viewType"));
                if("".equals(id)){//新增
                    isAdd = true;
                    calendar.setCreatedBy(userId);
                    calendar.setCorpId(corpId);
                    calendar.setIsMain("1");
                    if("share".equals(viewType)){
                        String sharedId = paramsMap.get("sharedId");
                        calendar.setCalendarOwner(sharedId);
                    }else{
                        calendar.setCalendarOwner(userId);
                    }
                }else{//日程编辑
                    calendar.setCalendarOwner(paramsMap.get("calendarOwner"));
                    if(!"no".equals(calendar.getDuplicateType())){//重复日程
                        String isMain = calendar.getIsMain();
                        if("".equals(type)){//主日程
                            calendar.setId(id);
                            if("1".equals(isMain)){
                                this.deleteByBelong(id);
                            }
                        }else{//重复日程
                            if("1".equals(isMain) && "current".equals(type)){//未修改过的重复日程
                                calendar.setId(null);
                                calendar.setBelongCalendar(id);
                                calendar.setIsMain("0");
                                calendar.setCreatedBy(userId);
                                calendar.setCorpId(corpId);
                                part = "";
                                viewer = "";
                                maintainer = "";
                                calendar.setCalendarOwner(paramsMap.get("calendarOwner"));
                            }
                            if("all".equals(type)){
                                this.updateMainCalendar(calendar);
                                String calendarId = id;
                                if("0".equals(isMain)){//已修改过的重复日程
                                    calendarId = calendar.getBelongCalendar();
                                }
                                calendar.setStartDate(startNow);
                                calendar.setEndDate(endNow);
                                this.deleteByBelong(calendarId);
                            }
                        }
                    }else{
                        calendar.setId(id);
                    }
                }

                if("".equals(part) || ("".equals(id) && !"".equals(type))){
                    part = UuidUtils.UUID();
                    calendar.setParticipant(part);
                }
                if("".equals(viewer) || ("".equals(id) && !"".equals(type))){
                    viewer = UuidUtils.UUID();
                    calendar.setViewer(viewer);
                }
                if("".equals(maintainer) || ("".equals(id) && !"".equals(type))){
                    maintainer = UuidUtils.UUID();
                    calendar.setMaintainer(maintainer);
                }
                String participantUser = StringUtils.null2String(paramsMap.get("participantUser"));
                if("[]".equals(participantUser)) {
                    participantUser = "";
                }
                String viewerUser = StringUtils.null2String(paramsMap.get("viewerUser"));
                if("[]".equals(viewerUser)) {
                    viewerUser = "";
                }
                String maintainerUser = StringUtils.null2String(paramsMap.get("maintainerUser"));
                if("[]".equals(maintainerUser)) {
                    maintainerUser = "";
                }
                this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, viewerUser, "oa_calendar", "viewer");
                this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer,maintainerUser , "oa_calendar", "maintainer");
                this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, participantUser, "oa_calendar", "participant");
            }
            //保存
            calendar = this.save(calendar);

            if(calendar!=null && !"".equals(calendar.getId())){
                resultMap.put("success", Boolean.valueOf(true));
                resultMap.put("content", "保存成功");

            }else{
                resultMap.put("success", Boolean.valueOf(false));
                resultMap.put("errorMsg", "保存失败");
                return resultMap;
            }

            //删除所有子日程编辑的信息
            this.deleteByBelong(calendar.getId());
            //删除  重复日程删除的日程信息
            this.deleteByBelong(calendar.getId());

            /**-----消息推送-----**/
            String participantUser = StringUtils.null2String(paramsMap.get("participantUser"));
            this.sendMessageForMobile(participantUser, calendar,corpId,token,request);

        }catch (Exception e) {
            resultMap.put("success", Boolean.valueOf(false));
            resultMap.put("errorMsg", "保存失败");
            LOG.error("保存失败",e);
            return resultMap;
        }
        return resultMap;

    }

    /**
     * 操作明细中重复的拼接
     * @param calendar
     * @param paramsMap
     * @return
     */
    public String getDuplicateInfo(Calendar calendar, Map<String, String> paramsMap) {
        String logMsg = "";
        if(calendar != null) {
            String duplicateType = calendar.getDuplicateType();
            if(!"no".equals(duplicateType)) {
                if("day".equals(duplicateType)) {
                    logMsg += "按天重复,每隔"+Integer.parseInt(calendar.getDuplicateInterval())+"天重复一次,";
                    if("always".equals(calendar.getDuplicateEndType()) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(calendar.getDuplicateEndType())) {
                        logMsg += "结束时间为"+calendar.getDuplicateEndTypeValue();
                    }else {
                        logMsg += "重复"+calendar.getDuplicateEndTypeValue()+"次后结束";
                    }
                }else if("week".equals(duplicateType)) {
                    logMsg += "按周重复,每周";
                    String weekString = calendar.getDuplicateInterval();
                    for (int i = 0; i < weekString.length(); i++) {
                        if(i == weekString.length()-1) {
                            logMsg += weekString.charAt(i)+"重复,";
                        }else {
                            logMsg += weekString.charAt(i)+"、";
                        }
                    }
                    if("always".equals(calendar.getDuplicateEndType()) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(calendar.getDuplicateEndType())) {
                        logMsg += "结束时间为"+calendar.getDuplicateEndTypeValue();
                    }else {
                        logMsg += "重复"+calendar.getDuplicateEndTypeValue()+"次后结束";
                    }

                }else if("month".equals(duplicateType)){
                    String dupStr = calendar.getWeekMonthDuplicateType();
                    String monthSelect = dupStr.substring(0,1);
                    logMsg += "按月重复,每" + monthSelect + "月" + dupStr.substring(1, dupStr.length()-1).split("month")[0] + "重复一次,";
                    if("always".equals(calendar.getDuplicateEndType()) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(calendar.getDuplicateEndType())) {
                        logMsg += "结束时间为"+calendar.getDuplicateEndTypeValue();
                    }else {
                        logMsg += "重复"+calendar.getDuplicateEndTypeValue()+"次后结束";
                    }
                }else if("year".equals(duplicateType)){
                    logMsg += "按年重复,每年"+Integer.parseInt(calendar.getDuplicateInterval())+"重复一次,";

                    if("always".equals(calendar.getDuplicateEndType()) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(calendar.getDuplicateEndType())) {
                        logMsg += "结束时间为"+calendar.getDuplicateEndTypeValue();
                    }else {
                        logMsg += "重复"+calendar.getDuplicateEndTypeValue()+"次后结束";
                    }
                }
            }else {
                logMsg = "不重复";
            }
        }else if(paramsMap != null) {
            String duplicateType = paramsMap.get("duplicateType");
            if(!"no".equals(duplicateType)) {
                if("day".equals(duplicateType)) {
                    logMsg += "按天重复,每隔"+Integer.parseInt(paramsMap.get("duplicateInterval"))+"天重复一次,";
                    if("always".equals(paramsMap.get("duplicateEndType")) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(paramsMap.get("duplicateEndType"))) {
                        logMsg += "结束时间为"+paramsMap.get("duplicateEndTypeValue");
                    }else {
                        logMsg += "重复"+paramsMap.get("duplicateEndTypeValue")+"次后结束";
                    }
                }else if("week".equals(duplicateType)) {
                    logMsg += "按周重复,每周";
                    String weekString = paramsMap.get("duplicateInterval");
                    for (int i = 0; i < weekString.length(); i++) {
                        if(i == weekString.length()-1) {
                            logMsg += weekString.charAt(i)+"重复,";
                        }else {
                            logMsg += weekString.charAt(i)+"、";
                        }
                    }
                    if("always".equals(paramsMap.get("duplicateEndType")) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(paramsMap.get("duplicateEndType"))) {
                        logMsg += "结束时间为"+paramsMap.get("duplicateEndTypeValue");
                    }else {
                        logMsg += "重复"+paramsMap.get("duplicateEndTypeValue")+"次后结束";
                    }

                }else if("month".equals(duplicateType)){
                    logMsg += "按月重复,每月"+Integer.parseInt(paramsMap.get("duplicateInterval"))+"日重复一次,";

                    if("always".equals(paramsMap.get("duplicateEndType")) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(paramsMap.get("duplicateEndType"))) {
                        logMsg += "结束时间为"+paramsMap.get("duplicateEndTypeValue");
                    }else {
                        logMsg += "重复"+paramsMap.get("duplicateEndTypeValue")+"次后结束";
                    }
                }else if("year".equals(duplicateType)){
                    logMsg += "按年重复,每年"+Integer.parseInt(paramsMap.get("duplicateInterval"))+"重复一次,";

                    if("always".equals(paramsMap.get("duplicateEndType")) ){
                        logMsg += "不结束";
                    }else if("endTime".equals(paramsMap.get("duplicateEndType"))) {
                        logMsg += "结束时间为"+paramsMap.get("duplicateEndTypeValue");
                    }else {
                        logMsg += "重复"+paramsMap.get("duplicateEndTypeValue")+"次后结束";
                    }
                }
            }else {
                logMsg = "不重复";
            }
        }
        return logMsg;
    }

    /**
     * 移送端新建日程消息推送
     * @param participantUser 要推送的人json串
     * @param calendar 日程实体类
     * @param corpId 单位id
     * @param token 身份信息
     * @param request 请求
     *
     */
    public void sendMessageForMobile(String participantUser, Calendar calendar, String corpId, String token,HttpServletRequest request){
        if (StringUtils.isNotBlank(participantUser) && !StringUtils.equals("[]",participantUser)) {
            List<Map<String, String>> list = (List<Map<String, String>>) JSONArray.parse(participantUser);
            String ids = "";
            for(Map<String,String> map : list){
                ids += map.get("scopeValue") + ",";
            }
            ids = ids.substring(0, ids.length()-1);
            //所属人信息
            Map<String,Object> userMap = userApiService.getUser(calendar.getCalendarOwner(),corpId,"",token);
            CalendarCategory calendarCategory = calendarCategoryService.findOne(calendar.getCalendarCategory());
            String start = "";
            String end = "";
            //是否是全天日程
            if ("1".equals(calendar.getIsAllDay())) {
                //全天日程 开始结束相同
                start = DateUtils.formatDate(calendar.getStartDate(),DateUtils.DEFAULT_DATE_FORMAT);
                end = start;
            }else{
                //不是全天日程    精确到分
                java.util.Calendar ca = java.util.Calendar.getInstance();
                ca.setTime(calendar.getStartDate());
                ca.add(java.util.Calendar.SECOND,calendar.getStartTime());
                start = DateUtils.formatDate(ca.getTime(),DateUtils.SHORT_TIME_FORMAT);

                ca.setTime(calendar.getEndDate());
                ca.add(java.util.Calendar.SECOND, calendar.getEndTime());
                end = DateUtils.formatDate(ca.getTime(),DateUtils.SHORT_TIME_FORMAT);
            }
            Map<String, String> paramMapApp = new HashMap<>();
            String repeat = "1";
            if ("no".equals(calendar.getDuplicateType())) {
                repeat = "0";
            }
            String columnValue = this.calendarSettingService.getCalendarColumn();
            paramMapApp.put("columnValue", columnValue);
            paramMapApp.put("isEdit","0");
            paramMapApp.put("repeat",repeat);
            paramMapApp.put("dataId", calendar.getId());
            paramMapApp.put("name",StringUtils.null2String(userMap.get("userName")));
            paramMapApp.put("cateName", calendarCategory.getName());
            paramMapApp.put("title", calendar.getTitle());
            paramMapApp.put("start", start);
            paramMapApp.put("end", end);
            paramMapApp.put("sendPath",this.getSysImType(corpId,token));
            paramMapApp.put("remindStyle", calendar.getRemindStyle());
            paramMapApp.put("ids", ids);
            paramMapApp.put("userId", calendar.getCalendarOwner());
            SendMessageDTO sendMessageDTO1 = new SendMessageDTO();
            SendMessageDTO sendMessageDTO2 = new SendMessageDTO();
            sendMessageDTO1.setModuleCode("calendar");
            sendMessageDTO2.setModuleCode("calendar");
            List<MessageBodyDTO> msgBodys1 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"umc","0");
            List<MessageBodyDTO> msgBodys2 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"mobile","0");
            sendMessageDTO1.setMsgBodys(msgBodys1);
            sendMessageDTO2.setMsgBodys(msgBodys2);
            List<String> msgTypes1 = new ArrayList<String>();
            List<String> msgTypes2 = new ArrayList<String>();
            msgTypes1.add("umc");
            msgTypes1.add("sms");
            msgTypes2.add("mobile");
            sendMessageDTO1.setMsgTypes(msgTypes1);
            sendMessageDTO1.setCorpId(corpId);
            sendMessageDTO1.setToken(token);
            sendMessageDTO1.setResourceType(ResourceTypes.SYSTEM.getCode());
            sendMessageApiService.sendMessage(sendMessageDTO1);
            sendMessageDTO2.setMsgTypes(msgTypes2);
            sendMessageDTO2.setCorpId(corpId);
            sendMessageDTO2.setToken(token);
            sendMessageDTO2.setResourceType(ResourceTypes.SYSTEM.getCode());
            sendMessageApiService.sendMessage(sendMessageDTO2);
        }

    }

    /**
     * 移动端日程删除
     * @param logCode 删除的日程类型  calendar 我的日程  leader 领导日程
     * @param id 要删除的日程id
     * @param eventDate 删除的日程的时间
     * @param type 删除类型  current-删除当前日程，after-删除当前及以后日程，all-删除所有日程，""-删除普通日程或主日程
     * @param corpId
     * @param token
     * @return Map<String, Object>  resultMap 删除结果状态
     *
     *
     */
    public Map<String, Object> deleteCalendarForMobile(String logCode, String id, String eventDate, String type, String corpId, String token){
        Map<String, Object> resultMap = new HashMap<>();

        if(StringUtils.equals(logCode, "calendar")) {//我的日程删除
            logCode = "calendar:mycalendar:04";
        }else if(StringUtils.equals(logCode, "leader")) {//领导日程删除
            logCode = "calendar:leader:04";
        }else if(StringUtils.equals(logCode, "sub")){
            logCode = "calendar:sub:04";
        }else if(StringUtils.equals(logCode, "share")){
            logCode = "calendar:shareMe:04";
        }

        try {
            Calendar calendar = this.findOne(id);
            Date start = new Date();
            //current-删除当前日程，after-删除当前及以后日程，all-删除所有日程，""-删除普通日程或主日程
            if("all".equals(type) || "".equals(type)){
                this.deleteByBelong(id);//删除日程
            }else{
                CalendarDelete delete  = new CalendarDelete();
                try {
                    start = CalendarUtils.getDataByStr(eventDate, "yyyy-MM-dd");
                } catch (Exception e) {
                    LOG.error("时间转换异常",e);
                }
                delete.setDeleteDate(start);
                if("0".equals(calendar.getIsMain())){
                    delete.setBelongCalendar(calendar.getBelongCalendar());
                }else{
                    delete.setBelongCalendar(id);
                }
                if("current".equals(type) || "after".equals(type)){
                    delete.setDeleteType(type);
                    this.calendarDeleteService.save(delete);
                    if("after".equals(type)){
                        this.deleteAfter(id, start);
                    }
                }
            }

            //删除提示信息
            List<String> ids = new ArrayList<>();
            ids.add(id);
            if("all".equals(type) || "".equals(type) || "0".equals(calendar.getIsMain())){
                this.delete(calendar);
                calendarSendMsgUtils.deleteMessage(ids,corpId,token);
            }

            //日志保存
            boolean logSet = this.logService.checkOptLog(corpId, logCode, token);
            if(logSet){
                logService.saveModuleLog(logCode, calendar.getTitle(), "");
            }

            /****同步删除evoportal日程开始****/
            Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(corpId,"calendarSync");
            String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
            //重复日程不同步
            if(calendarSync.contains("evoPortal") && "no".equals(calendar.getDuplicateType())){
                try {
                    this.calendarDeleteToEvoPortal(calendar,corpId);
                }catch (Exception e){
                    LOG.error("同步删除日程失败",e);
                }
            }
            /****同步删除evoportal日程结束****/

            resultMap.put("code", "1");
            resultMap.put("success", true);
            resultMap.put("message", "成功");
            return resultMap;
        }catch (Exception e){
            resultMap.put("code", "-1");
            resultMap.put("success", false);
            resultMap.put("message", "失败");
            LOG.error("删除日程失败！",e);
            return resultMap;
        }
    }

    /**
     * 移动端获取日程详情所需列字段
     * @param requestParams 移动端返回的参数json串
     * @param corpId 单位Id
     * @param token 身份信息
     * @param userId 登录人Id
     * @param userName 登录人姓名
     * @return Map<String, Object> result
     *
     */
    public Map<String, Object> getPersonNameForMobile(String requestParams, String corpId, String token, String userId, String userName){
        long n1 = System.currentTimeMillis();
//        LOG.error("personNamek开始："+n1);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("success", true);
        result.put("message", "成功");
        Map<String, Object> content = new HashMap<>();

        Map<String, Object> paramsMap = null;
        paramsMap = JsonUtils.readValue(requestParams);
        String id = StringUtils.null2String(paramsMap.get("id"));
        Calendar calendar =null;
        if(StringUtils.isNoneBlank(id)) {
            calendar = this.findOne(id);
        }
        if(calendar != null ) {
            Map<String, Object> map = userApiService.getUser(calendar.getCreatedBy(), corpId,"" , token);
            content.put("userName", map.get("userName"));
            content.put("userId", map.get("id"));
        }else {
            content.put("userName", userName);
            content.put("userId", userId);
        }

        Map<String,String> settingMap = this.calendarSettingService.getCanlenderFieldSetting(corpId);
        content.put("settingMap", settingMap);
        result.put("content", content);
//        LOG.error("personNamek结束："+(System.currentTimeMillis()-n1));

        return result;
    }

    /**
     * 获取当前整个月的日程
     * @param request 接口request
     * @param userName 登录人姓名
     * @param userId 用户id
     * @param corpId 单位id
     * @param token 身份信息
     * @return  result Map<String, Object> 结果集
     *
     */
    public Map<String, Object> searchCalendarListResult(HttpServletRequest request, String userName, String userId, String corpId, String token) throws ParseException {

        String orgId = StringUtils.null2String(request.getParameter("orgId"));//组织id
        String typeId = StringUtils.null2String(request.getParameter("typeId"));//分类id
        String category = StringUtils.null2String(request.getParameter("category"));//空值
        String viewType = StringUtils.null2String(request.getParameter("viewType"));// 查看入口  mine  share
        String search = StringUtils.null2String(request.getParameter("search")).trim();//搜索内容
        String searchTime = StringUtils.null2String(request.getParameter("searchTime"));//搜索时间
        String userIdPhone = StringUtils.null2String(request.getParameter("userId"));//共享id
        String logCode = StringUtils.null2String(request.getParameter("logCode"));//共享id
        String sharedId = "";
        if("share".equals(viewType)){
            sharedId = userIdPhone;//共享id
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("success", true);
        result.put("message", "成功");
        Map<String, Object> content = new HashMap<>();
        content.put("userName", userName);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, String>> calendarList = new ArrayList<>();
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        Object[] object;
        String start = "";
        String end = "";
        String shareId = "";
        if(searchTime.isEmpty()) {
            String year = CalendarUtils.getStrByDate(new Date(), "yyyy");
            String month = CalendarUtils.getStrByDate(new Date(), "MM");
            String yearMonth =  CalendarUtils.getStrByDate(new Date(), "yyyy-MM");
            int day = CalendarUtils.getMonthMaxDay(Integer.parseInt(year), Integer.parseInt(month)-1);
            object = new Object[day+1];
            start = yearMonth+"-01";
            end = yearMonth+"-"+day;
        }else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            if(searchTime.indexOf("-")==-1) {
                long lt = Long.parseLong(searchTime);
                Date date = new Date(lt);
                searchTime = simpleDateFormat.format(date);
            }
            String[] dateValue = searchTime.split("-");
            int day = CalendarUtils.getMonthMaxDay(Integer.parseInt(dateValue[0]), Integer.parseInt(dateValue[1])-1);//获取当月的最大的一天
            object = new Object[day+1];
            String[] dateStr = searchTime.split("-");
            if(dateStr[1].length()==1) {
                searchTime = dateStr[0]+"-0"+dateStr[1];
            }
            start = searchTime+"-01";
            end = searchTime+"-"+day;
        }
        String leaderOrSub = request.getParameter("leaderOrSub");
        boolean shareFlag = false;//共享日程标识
        Map<String, String> canEditLeaders = new HashMap<String, String>();
        if (StringUtils.equals("1", leaderOrSub)) {
            if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {//领导日程
                Map<String,String> leaderMap = this.calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(typeId,userId,corpId,token,orgId);
                StringBuffer sb = new StringBuffer();
                if(MapUtils.isNotEmpty(leaderMap)) {
                    for(String leaderId : leaderMap.keySet()) {
                        sb.append(leaderId + ",");
                    }
                    shareId = sb.toString().substring(0,sb.toString().length()-1);
                }else {
                    shareId = "";
                }
                canEditLeaders = this.calendarLeaderSettingService.getLeaderIdsByUserIdAndCategoryId("", userId, "", corpId, typeId, token);
            }else {
                shareId = StringUtils.null2String(request.getParameter("userId"));
            }
            calendarList = this.getOaCalendarAllSearch(pageable, "", category, shareId, corpId, "", viewType, start, end, token, search, searchTime, leaderOrSub);
        }else{
            if("share".equals(viewType)) {
                shareFlag = true;
                List<Map<String, String>> shareList = this.getShareOwner(userId, corpId, token);
                if(CollectionUtils.isNotEmpty(shareList)) {
                    for(Map<String,String> map : shareList) {
                        List<Map<String, String>> calendarListOne = this.getOaCalendarAllSearch(pageable, map.get("userId"), category, userId, corpId, "", viewType, start, end, token, search, searchTime, leaderOrSub);
                        if(CollectionUtils.isNotEmpty(calendarListOne)) {
                            for(Map<String, String> eventMap : calendarListOne) {
                                eventMap.put("userName", map.get("name"));
                            }
                        }
                        calendarList.addAll(calendarListOne);
                    }
                }
            }else {
//                LOG.error("searchList-getAll开始："+System.currentTimeMillis());
                calendarList = this.getOaCalendarAllSearch(pageable, sharedId, category, userId, corpId, "", viewType, start, end, token, search, searchTime, leaderOrSub);
//                LOG.error("searchList-getAll结束:"+System.currentTimeMillis());
            }
        }

        if("leader".equals(logCode)){
            calendarList = this.changePartToLeaderName(calendarList, shareId, corpId, token,"");
        }
//        LOG.error("searchList-datas开始："+System.currentTimeMillis());
        if(calendarList!=null && calendarList.size()>0) {
            for(int i=0;i<calendarList.size();i++) {
                List<Map<String, String>> newCalendar = new ArrayList<>();
                String time = calendarList.get(i).get("start").substring(8, 10);
                String calendarOwner = calendarList.get(i).get("calendarOwner");
                String leader  = calendarList.get(i).get("leader");
                if(canEditLeaders != null) {
                    if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(calendarOwner)))) {
                        calendarList.get(i).put("canEdit", "yes");
                    }else {
                        calendarList.get(i).put("canEdit", "no");
                    }
                    if(StringUtils.isNotEmpty(StringUtils.null2String(canEditLeaders.get(leader)))){
                        calendarList.get(i).put("canComplete", "yes");
                    }


                }else {
                    calendarList.get(i).put("canEdit", "no");
                }
                Integer num = Integer.parseInt(time);
                if(object[num] == null) {
                    newCalendar.add(calendarList.get(i));
                    object[num] = newCalendar;
                }else {
                    newCalendar = (List<Map<String, String>>) object[num];
                    newCalendar.add(calendarList.get(i));
                    object[num] = newCalendar;
                }
            }
            for (int i = 0;i<object.length;i++) {
                List<Map<String, String>> newCalendar = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                if(object[i] != null) {
                    newCalendar = (List<Map<String, String>>) object[i];
                    map.put("date", newCalendar.get(0).get("startDate"));
                    map.put("events",newCalendar);
                    list.add(map);
                }
            }
        }
//        LOG.error("searchList-datas结束："+System.currentTimeMillis());
        content.put("datas", list);

        //处理list按 日期-日程分类-分类下日程三层结构;
        for(Map<String,Object> map : list) {
            Map<String,List<Map<String, String>>> maps = new HashMap();
            List<Map> lists = (List)map.get("events");
            if(CollectionUtils.isNotEmpty(lists)) {
                if(shareFlag) {
                    for(Map<String, String> sigleDayCalendar :lists) {
                        String category1 = sigleDayCalendar.get("userName").toString();
                        maps.put(category1, new ArrayList<Map<String, String>>());
                    }
                    for(Map<String, String> map1 :lists) {
                        String category2 = map1.get("userName");
                        maps.get(category2).add(map1);
                    }
                }else {
                    if(StringUtils.isNotEmpty(orgId) && !"null".equals(orgId)) {

                        if(CollectionUtils.isNotEmpty(lists)){
                            List<Map<String,String>> dataList = new ArrayList<Map<String, String>>();
                            String category1 = "leaderCalendar";
                            for(Map<String, String> map1 :lists) {
                                dataList.add(map1);
                            }
                            maps.put(category1, dataList);
                        }

//                        for(Map<String, String> sigleDayCalendar :lists) {
//                            String category1 = "leaderCalendar";
//                            maps.put(category1, new ArrayList<Map<String, String>>());
//                        }
//                        for(Map<String, String> map1 :lists) {
//                            String category2 = "leaderCalendar";
//                            maps.get(category2).add(map1);
//                        }
                    }else {
                        for(Map<String, String> sigleDayCalendar :lists) {
                            String category1 = sigleDayCalendar.get("category").toString();
                            maps.put(category1, new ArrayList<Map<String, String>>());
                        }
                        for(Map<String, String> map1 :lists) {
                            String category2 = map1.get("category");
                            maps.get(category2).add(map1);
                        }
                    }
                }
            }
            List list1 = new ArrayList();
            for (Map.Entry<String,List<Map<String, String>>> entry : maps.entrySet()) {
                List<Map<String, String>> sortList = entry.getValue();
                CalendarUtils.sortResultList(sortList,"isAllDay","start");
                Map<String,Object> allDayEvents = new HashMap();
                allDayEvents.put("cate", entry.getKey());
                allDayEvents.put("calendars", entry.getValue());
                list1.add(allDayEvents);
            }
            map.put("allDayEvent", list1);
        }
//        LOG.error("searchList-content："+System.currentTimeMillis());

        result.put("content", content);
        return result;
    }


    /**
     * 获取所有共享日程给当前用户共享人
     * @param userId 用户id
     * @param token 身份信息
     * @param corpId 单位Id
     * @param subOrShare 标识位  sub 下级  共享
     * @param searchName 搜索字段
     * @return list List<Map<String, String>> 结果集
     *
     */
    public List<Map<String, String>> getShareUsersForMobile(String userId, String token, String corpId, String subOrShare, String searchName){
        List<Map<String, String>> list = new ArrayList<>();
        if(StringUtils.equals("sub", subOrShare)) {//下级
            //下级用户
            List<Map<String, String>> subUserList = this.getSubStaff(userId, token);
            List<String> subIds = subUserList.stream().map(map -> { return map.get("userId"); }).collect(Collectors.toList());
            List<Map<String, String>> subUserInfoList = this.getUserInfo(subIds, corpId, token);
            if (CollectionUtils.isNotEmpty(subUserInfoList)) {
                for (Map<String, String> map : subUserInfoList) {
                    map.put("type", "sub");
                }
            }
            list.addAll(subUserInfoList);
        }else {//共享
            //获取共享用户
            List<Map<String, String>> shareList = this.getShareOwner(userId, corpId, token);
            list.addAll(shareList);
        }

        //名字
        if (StringUtils.isNotBlank(searchName)) {
            //姓名查询
            List<Map<String, String>> lists = new ArrayList<>();
            String name = "";
            for (Map map : list) {
                name = StringUtils.null2String(map.get("name"));
                if (name.indexOf(searchName) >= 0) {
                    lists.add(map);
                }
            }
            list = lists;
        }
        List<Map<String, String>> shareds = new ArrayList<>();

        String fileNames = "";
        for (Map<String, String> map : list) {
            String fileName = StringUtils.null2String(map.get("fileName"));
            fileNames = fileNames+","+fileName;
        }
        if(fileNames.length()>0) {
            fileNames = fileNames.substring(1);
        }
        //获取附件信息
        Map<String,Map<String,String>> attachmentMap = new HashMap<>();
        if(StringUtils.isNotEmpty(fileNames)) {
            List<Map<String,String>> attachmentList = this.attachmentUtilsService.getAttachmentByFileNames(fileNames,corpId,token);
            if(CollectionUtils.isNotEmpty(attachmentList)){
                for(Map<String,String> att : attachmentList) {
                    attachmentMap.put(att.get("fileName"), att);
                }
            }

        }


        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = list.get(i);
            String fileName = StringUtils.null2String(map.get("fileName"));
            if (!"".equals(fileName)) {
                Map<String, String> image = attachmentMap.get(fileName);
                if (image != null && !image.isEmpty()) {
                    map.put("image", image.get("id"));
                } else {
                    map.put("image", "");
                }
            } else {
                map.put("image", "");
            }
            String sharedId = map.get("userId");
            String orgName = this.findUserOrg(sharedId);
            map.put("orgName", orgName);
            String isCreated = this.calendarCategoryService.isCreatedWithShare(userId, sharedId);
            String isMaintain = this.calendarCategoryService.isMaintainWithShare(userId, sharedId, corpId, token);
            map.put("isCreated", isCreated);
            map.put("isMaintain", isMaintain);
            shareds.add(map);
        }

        return list;
    }

    /**
     * 获取领导人信息
     * @param searchName 搜索内容
     * @param userId 用户id
     * @param corpId 单位id
     * @param token 身份信息
     * @return list List<Map<String, String>> 结果集
     *
     */
    public List<Map<String, String>> getLeaderUsersForMobile(String searchName, String userId, String corpId, String token){
        Map<String, String> leaderMap = calendarLeaderSettingService.getAllLeader(searchName, userId, corpId, token);
        List<String> ids = new ArrayList<>();
        for (Map.Entry<String, String> entry : leaderMap.entrySet()) {
            ids.add(entry.getKey());
        }
        List<Map<String, String>> list = this.getUserInfo(ids, corpId, token);
        //名字
        if (StringUtils.isNotBlank(searchName)) {
            //姓名查询
            List<Map<String, String>> lists = new ArrayList<>();
            String name = "";
            for (Map map : list) {
                name = StringUtils.null2String(map.get("name"));
                if (name.indexOf(searchName) >= 0) {
                    lists.add(map);
                }
            }
            list = lists;
        }
        String fileNames = "";
        for (Map<String, String> map : list) {
            String fileName = StringUtils.null2String(map.get("fileName"));
            fileNames = fileNames+","+fileName;
        }
        if(fileNames.length()>0) {
            fileNames = fileNames.substring(1);
        }
        //获取附件信息
        Map<String,Map<String,String>> attachmentMap = new HashMap<>();
        if(StringUtils.isNotEmpty(fileNames)) {
            List<Map<String,String>> attachmentList = this.attachmentUtilsService.getAttachmentByFileNames(fileNames,corpId,token);

            for(Map<String,String> att : attachmentList) {
                attachmentMap.put(att.get("fileName"), att);
            }
        }


        for (Map<String, String> map : list) {
            String fileName = StringUtils.null2String(map.get("fileName"));

            if (!"".equals(fileName)) {
                Map<String, String> image = attachmentMap.get(fileName);
                if (image != null && !image.isEmpty()) {
                    map.put("image", image.get("id"));
                } else {
                    map.put("image", "");
                }
            } else {
                map.put("image", "");
            }
            String leaderId = map.get("userId");
            String orgName = this.findUserOrg(leaderId);
            map.put("orgName", orgName);
            String leaderNameAndType = leaderMap.get(leaderId);
            String[] arr = leaderNameAndType.split("_");
            if (StringUtils.equals("view", arr[1])) {
                map.put("isEdit", "no");
            } else if (StringUtils.equals("maintainer", arr[1])) {
                map.put("isEdit", "yes");
            }
        }

        return list;
    }

    /**
     * 验证日程是否重叠
     * @param requestParams 参数json串
     * @param corpId 单位id
     * @param userId 用户id
     * @param token 身份信息（令牌）
     *
     *
     */
    public Map<String, Object> checkRepeatForMobile(String requestParams, String corpId, String userId, String token,WebUser user) throws ParseException {
        Map<String, String> paramsMap = null;
        Map<String, Object> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            paramsMap = (Map) mapper.readValue(requestParams, Map.class);
        } catch (IOException e) {
            LOG.error("转换异常",e);
        }
        String viewType = "calendar";
        String sharedId = "";
        String title = "";
        String category = "";
        String leader = "";
        String start = paramsMap.get("startTime").substring(0,10);
        String end = paramsMap.get("endTime").substring(0,10);
        String stm = paramsMap.get("startTime").substring(paramsMap.get("startTime").length()-5,paramsMap.get("startTime").length()).trim();
        String etm = paramsMap.get("endTime").substring(paramsMap.get("endTime").length()-5,paramsMap.get("endTime").length()).trim();
        String isAllDay = paramsMap.get("isAllDay");
        String mainId = StringUtils.null2String(paramsMap.get("id"));
        String leaderOrSubId = StringUtils.null2String(paramsMap.get("sharedId"));
        if("1".equals(isAllDay)) {
            stm = "00:00";
            etm = "23:59";
            end = start;
        }
        String flag = "0";
        String result;
        if(leaderOrSubId!="") {
//            LOG.error("开始结果测试："+System.currentTimeMillis());
            result = this.getOaCalendar(sharedId, leaderOrSubId, corpId, title, category,viewType, start, end, token,leader,user);
//            LOG.error("结束结果测试："+System.currentTimeMillis());
        }else {
            result = this.getOaCalendar(sharedId, userId, corpId, title, category,viewType, start, end, token,leader,user);
        }
//        LOG.error("循环开始："+System.currentTimeMillis());
        if(!"[]".equals(result)) {
            JSONArray json = JSONArray.parseArray(result);
            for (int i = 0; i < json.size(); i++) {
                JSONObject job = json.getJSONObject(i);
                String id = job.get("mainId")+"";
                if(id.equals(mainId)) {
                    continue;
                }
                String startTime = job.get("start")+"";
                String endTime = job.get("end")+"";
                String stm2;
                String etm2;
                if(startTime.indexOf("T")<0 && "null".equals(endTime)) {
                    startTime = startTime +"T";
                    endTime = startTime;
                    stm2 = "00:00";
                    etm2 = "23:59";
                }else {
                    stm2 = startTime.substring(startTime.indexOf("T")+1,startTime.length());
                    etm2 = endTime.substring(endTime.indexOf("T")+1,endTime.length());
                }
                String start2 = startTime.substring(0,startTime.indexOf("T"));
                String end2 = endTime.substring(0,endTime.indexOf("T"));
                if(!start.equals(end) && !start2.equals(end2)) {
                    if(end2.equals(start)) {
                        if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else if(end.equals(start2)) {
                        if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else {
                        flag = "1";
                        break;
                    }
                }else if(!start.equals(end) && start2.equals(end2)) {
                    if(start.equals(end2)) {
                        if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else if(end.equals(start2)) {
                        if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else {
                        flag = "1";
                        break;
                    }
                }else if(start.equals(end) && !start2.equals(end2)) {
                    if(end2.equals(start)) {
                        if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else if(start2.equals(start)) {
                        if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
                            flag = "0";
                        }else {
                            flag = "1";
                            break;
                        }
                    }else {
                        flag = "1";
                        break;
                    }
                }else if(start.equals(end) && start2.equals(end2) && start.equals(start2)){
                    if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
                        flag = "0";
                    }else if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
                        flag = "0";
                    }else {
                        flag = "1";
                        break;
                    }
                }else {
                    flag = "0";
                }
            }
        }

//        LOG.error("循环结束："+System.currentTimeMillis());

        map.put("flag", flag);

        return map;
    }

    /**
     * 查询可查看的所有领导日程分类和分类下所有可查看的领导所在的组织
     * @param userId 用户id
     * @param corpId 单位id
     * @param token 身份信息
     * @param searchOrgName 搜索内容
     * @return Map<String, Object>  categoryAndOrg 结果集
     *
     */
    public Map<String, Object> findCategoryAndOrgs (String userId, String corpId, String token, String searchOrgName){
        Map<String, Object> categoryAndOrg = new HashMap<String, Object>();
        Map<String, Object> orgMap = new HashMap<String, Object>();
        //先查询登录人可查看到的所有领导日程分类
        List<Map> categoryList = calendarLeaderCategoryService.findCategoryInViewScope(userId,corpId);
        List<Map> categoryListNew = new ArrayList<Map>();
        for (int i = 0; i < categoryList.size(); i++) {
            String categoryId = categoryList.get(i).get("id")+"";
            //在根据领导日程分类id查出所有可见的领导
            Map<String, String> leaderMap = calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(categoryId, userId, corpId, token, "");
            Set<String> leaderIds = null;
            List<String> leaderIdList = null;
            List<Map> orgList = null;
            if(leaderMap != null) {
                leaderIds = leaderMap.keySet();
                leaderIdList = new ArrayList<>(leaderIds);
                orgList = calendarLeaderSettingService.findAllOrgByLeaderIds(leaderIdList, corpId, searchOrgName);
            }
            //查出各领导所在的组织
            if(CollectionUtils.isNotEmpty(orgList)){
                orgMap.put(categoryId, orgList);
            }
        }
        for (String categoryId : orgMap.keySet()) {
            for (Map map : categoryList) {
                if(StringUtils.equals(categoryId, StringUtils.null2String(map.get("id")))) {
                    categoryListNew.add(map);
                }
            }
        }
        categoryAndOrg.put("category", categoryListNew);
        categoryAndOrg.put("orgMap", orgMap);

        return categoryAndOrg;
    }

    /**
     * 获取日程自定义周视图数据(我的日程/领导日程)
     * @param leader 1 领导日程
     * @param pageable requestq 请求分页参数
     * @param category  日程分类
     * @param sharedId 共享人id
     * @param corpId 单位id
     * @param title 搜索标题
     * @param start 搜索开始时间
     * @param end 搜索结束时间
     * @param token 身份信息
     * @param userId 登录人id
     * @param custWeekType
     * @param viewType
     * @param ingOrFinish 选择了进行中或者已完成
     * @param selectViewType 选中的视图  我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar  自定义 customCalendar
     *
     * @return PageImpl 处理好的分页数据
     */
    public PageImpl getOaWeekCalendarResult(String leader, Pageable pageable, String category, String sharedId, String corpId, String title, String start, String end, String token,
                         String userId, String custWeekType, String viewType, String ingOrFinish, String selectViewType){
        List<Map<String, String>> result = new ArrayList<>();
        //领导、下属、共享、自定义日程周视图按时间排序
        if (!"myCalendar".equals(selectViewType)) {
            if("shareCalendar".equals(selectViewType)){
                result = this.getOaCalendarList(pageable, sharedId,category, userId, corpId, title,viewType, start, end, token, userId,"calendar",ingOrFinish,custWeekType);
            }else{
                result = this.getOaCalendarList(pageable, "",category, sharedId, corpId, title,"calendar", start, end, token, userId,"leaderOrSubCalendar","",custWeekType);

                //在这里对数据进行处理
                result = changePartToLeaderName(result, sharedId, corpId, token,"");

            }


            //平行越权处理
            Map<String, String> extMap = new HashMap<>();
            extMap.put("userId",userId);
            result = CalendarSecUtils.calendarEncodeListByIdUserIdString(result,extMap);

            //根据map中的startWeek字段进行排序
            if(CollectionUtils.isNotEmpty(result) && StringUtils.equals("1", custWeekType)) {
                //对集合进行排序
                CalendarUtils.sortResultList(result,"isAllDay","startWeek");

                return new PageImpl(result);
            }else {//领导日程周视图按领导排序
                List<Map<String, String>> list = new ArrayList<>();
                Map<String, Map<String, String>> bigMap = new LinkedHashMap<>();
                Map<String,String> leaderCalendarMap = null;
                for (Map<String, String> map : result) {
                    String owner = map.get("calendarOwner");
                    String leaderId = StringUtils.null2String(map.get("leader"));
                    if(StringUtils.isNotBlank(leaderId)){
                        owner = leaderId;
                    }
                    String isAmOrPm = map.get("isAmOrPm");
                    String key = owner+isAmOrPm;
                    if(bigMap.get(key) == null) {
                        leaderCalendarMap = new HashMap<>();
                        leaderCalendarMap.put("owner", map.get("owner"));
                        leaderCalendarMap.put("isAmOrPm", isAmOrPm);
                        leaderCalendarMap.put("monday", "");
                        leaderCalendarMap.put("tuesday", "");
                        leaderCalendarMap.put("wednesday", "");
                        leaderCalendarMap.put("thursday", "");
                        leaderCalendarMap.put("friday", "");
                        leaderCalendarMap.put("saturday", "");
                        leaderCalendarMap.put("sunday", "");
                    }else {
                        leaderCalendarMap = bigMap.get(key);
                    }
                    String weekNumber = map.get("weekNumber");
                    String startTime = map.get("startWeek").substring(11,16);
                    if ("00:00".equals(startTime)) {
                        startTime = "";
                    }
                    String calTitle = map.get("title");
                    String degreeOfImportance = map.get("degreeOfImportance");
                    String belong = map.get("belong");
                    String categoryVal = map.get("category");
                    String isComplate = map.get("isComplate");
                    String id = map.get("id");
                    String repeat = map.get("repeat");
                    String startDate = map.get("start");
                    String endDate = map.get("end");
                    String secdatacode = map.get("secdatacode");
                    StringBuilder value = new StringBuilder();
                    value.append(degreeOfImportance).append(",").append(belong).append(",").append(categoryVal).append(",").append(isComplate)
                            .append(",").append(id).append(",").append(repeat).append(",").append(startDate).append(",").append(endDate).append(",").append(secdatacode).append(",").append(leaderId);
                    if(StringUtils.equals("星期一", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("monday"))) {
                            leaderCalendarMap.put("monday", startTime+" "+calTitle);
                            leaderCalendarMap.put("mondayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("monday", leaderCalendarMap.get("monday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("mondayValue", leaderCalendarMap.get("mondayValue")+"flexSplit"+value);
                        }
                    }else if(StringUtils.equals("星期二", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("tuesday"))) {
                            leaderCalendarMap.put("tuesday", startTime+" "+calTitle);
                            leaderCalendarMap.put("tuesdayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("tuesday", leaderCalendarMap.get("tuesday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("tuesdayValue", leaderCalendarMap.get("tuesdayValue")+"flexSplit"+value);
                        }
                    }else if(StringUtils.equals("星期三", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("wednesday"))) {
                            leaderCalendarMap.put("wednesday", startTime+" "+calTitle);
                            leaderCalendarMap.put("wednesdayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("wednesday", leaderCalendarMap.get("wednesday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("wednesdayValue", leaderCalendarMap.get("wednesdayValue")+"flexSplit"+value);
                        }
                    }else if(StringUtils.equals("星期四", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("thursday"))) {
                            leaderCalendarMap.put("thursday", startTime+" "+calTitle);
                            leaderCalendarMap.put("thursdayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("thursday", leaderCalendarMap.get("thursday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("thursdayValue", leaderCalendarMap.get("thursdayValue")+"flexSplit"+value);
                        }
                    }else if(StringUtils.equals("星期五", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("friday"))) {
                            leaderCalendarMap.put("friday", startTime+" "+calTitle);
                            leaderCalendarMap.put("fridayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("friday", leaderCalendarMap.get("friday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("fridayValue", leaderCalendarMap.get("fridayValue")+"flexSplit"+value);
                        }
                    }else if(StringUtils.equals("星期六", weekNumber)) {
                        if(StringUtils.isBlank(leaderCalendarMap.get("saturday"))) {
                            leaderCalendarMap.put("saturday", startTime+" "+calTitle);
                            leaderCalendarMap.put("saturdayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("saturday", leaderCalendarMap.get("saturday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("saturdayValue", leaderCalendarMap.get("saturdayValue")+"flexSplit"+value);
                        }
                    }else {
                        if(StringUtils.isBlank(leaderCalendarMap.get("sunday"))) {
                            leaderCalendarMap.put("sunday", startTime+" "+calTitle);
                            leaderCalendarMap.put("sundayValue", value.toString());
                        }else {
                            leaderCalendarMap.put("sunday", leaderCalendarMap.get("sunday")+"flexSplit"+startTime+" "+calTitle);
                            leaderCalendarMap.put("sundayValue", leaderCalendarMap.get("sundayValue")+"flexSplit"+value);
                        }
                    }
                    bigMap.put(key, leaderCalendarMap);
                }
                Set<String> keys = bigMap.keySet();
                for (Map.Entry<String, Map<String, String>> entry : bigMap.entrySet()) {
                    Map<String, String> map = entry.getValue();
                    list.add(map);
                }
                return new PageImpl(list);
            }
        }
        result = this.getOaCalendarList(pageable, sharedId,category, userId, corpId, title,viewType, start, end, token, userId,"calendar",ingOrFinish,"");
        //根据map中的startWeek字段进行排序
        if(CollectionUtils.isNotEmpty(result)) {
            //对结果进行排序
            CalendarUtils.sortResultList(result,"isAllDay","startWeek");
        }
        Map<String, String> extMap = new HashMap<>();
        extMap.put("userId",userId);
        return new PageImpl(CalendarSecUtils.calendarEncodeListByIdUserIdString(result,extMap));

    }

    /**
     * 获取日程自定义日视图数据(我的日程/领导日程/下属日程/共享日程)
     * @param leader 1 领导日程
     * @param sharedId 共享人id
     * @param corpId 单位Id
     * @param title 搜索标题
     * @param category 日程分类
     * @param start 搜索开始时间
     * @param end 搜索结束时间
     * @param selectViewType 选择的视图 我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar
     * @param leaderTimeSettingType 开始时间/上午下午 1 上午下午
     * @param userId 登录人id
     * @param viewType 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
     * @param ingOrFinish 选择了进行中/已完成
     * @param myCalendar 我的日程 1
     * @param shareId 共享id
     *
     * @return 分页数据 PageImpl
     */
    public PageImpl getOaDayCalendarResult(String leader, String sharedId, String corpId, String title, String category, String start, String end, String token,
                         String selectViewType, String leaderTimeSettingType, String userId, String viewType, String ingOrFinish, String myCalendar, String shareId, WebUser user) throws ParseException {
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> mapResult = new ArrayList<>();
        String result = "";
        //如果是领导日程，组装数据结构用于前端多级表头显示
        if (StringUtils.isNotBlank(leader)) {
            result = this.getOaCalendar("", sharedId, corpId, title, category,"calendar", start, end, token,leader,user);
            if (StringUtils.isNotBlank(result)){
                //领导日程，对参与人进行处理
                JSONArray ja = JSONArray.parseArray(result);
                List<Map<String,String>> resultListTem = JSONArray.toJavaObject(ja,List.class);
                resultListTem = this.changePartToLeaderName(resultListTem, sharedId, user.getCorpId(), user.getJwtToken(),"");
                resultList = (List<Map<String, Object>>) JSONArray.parse(JSONArray.toJSONString(resultListTem));

            }

            //排序
            CalendarUtils.sortResultList(resultList,"startTime");

            /****************************组装结果 start******************************/
            // 领导id集合
            List<String>  leaderIdList= Arrays.asList(sharedId.split(","));
            // 上午
            HashMap<String, Object> map11 = new HashMap<>();
            // 下午
            HashMap<String, Object> map22 = new HashMap<>();
            // 20220111 从map集合中获取所有参与日程类型，放到新的集合单独进行处理，其余日程也放到新的集合单独进行处理
            List<Map<String,Object>> mapList = new ArrayList<>();
            mapList = resultList;
//            List<Map<String,Object>> partMapList = new ArrayList<>();

//            for (int i = 0; i < map.size(); i++) {
//                String calendarIsPart = String.valueOf(null==map.get(i).get("isPart") ? "" : map.get(i).get("isPart"));
//                if (StringUtils.isNotBlank(calendarIsPart)) {
//                    // 参与日程添加到新的集合partMapList
//                    partMapList.add(map.get(i));
//                } else {
//                    // 非参与日程添加到新的集合mapList
//                    mapList.add(map.get(i));
//                }
//            }
            for (int j = 0; j < leaderIdList.size(); j++) {
                // 日程所属人员id
                String leaderId = leaderIdList.get(j);
                // 上午-日程id
                StringBuilder sbAmCid = new StringBuilder();
                // 上午-日程名称
                StringBuilder sbAmCname = new StringBuilder();
                // 下午-日程id
                StringBuilder sbPmCid = new StringBuilder();
                // 下午-日程名称
                StringBuilder sbPmCname = new StringBuilder();
                for (int i = 0; i < mapList.size(); i++) {
                    // 这里选择日程要显示的领导、下属
                    String calendarOwner = mapList.get(i).get("calendarOwner") + "";
                    String leaderPartId = "";
                    if("1".equals(mapList.get(i).get("isPart"))){
                        leaderPartId = mapList.get(i).get("leader")+"";
                        calendarOwner = leaderPartId;
                    }
                    String calendarName = mapList.get(i).get("title") + "";
                    String secdatacode =  mapList.get(i).get("secdatacode") + "";
                    String startTime = CalendarUtils.getTime(Integer.parseInt(mapList.get(i).get("startTime")+""));
                    boolean isAllDay = (boolean) mapList.get(i).get("allDay");
                    String amOrPm = StringUtils.null2String(mapList.get(i).get("amOrPm"));
                    String isAmOrPm = StringUtils.null2String(mapList.get(i).get("isAmOrPm"));

                    if("1".equals(amOrPm)){
                        if("1".equals(isAmOrPm)){
                            startTime = "9:00";
                        }else{
                            startTime = "14:00";
                        }
                    }

                    if(isAllDay){
                        startTime = "";
                    }

                    if(StringUtils.isNotBlank(calendarName)){
                        calendarName = calendarName.replace("<", "&lt;").replace(">", "&gt;");
                    }
                    // 20210831 日程标记完成功能：判断当前用户是否完成指定日程
                    String isComplate = "0";

                    //2022-03-31
                    if("true".equals(mapList.get(i).get("isComplate"))){
                        isComplate = "1";
                    }

                    // 20220111 属于当前用户的日程  *  2022-01-16新增领导日程判断
                    if ("1".equals(isAmOrPm) && ("customCalendar".equals(selectViewType) || "subCalendar".equals(selectViewType) || "leaderCalendar".equals(selectViewType)) && leaderId.equals(calendarOwner)) { //上午
                        /*2022018-判断领导日视图是否重要，重要则加标志*/
                        if("2".equals(mapList.get(i).get("degreeOfImportance"))){
                            sbAmCname.append("<span style=\"margin-right:4px\"><i class=\"iconfont icon-important text-red\"></i></span>");
                        }
                        // 开启上午/下午模式
                        if ("1".equals(leaderTimeSettingType)){
                            if (calendarName.length()>20){
                                sbAmCname.append("<a href=\"javascript:; data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" title=\""+calendarName+"\" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+ " data-startTime="+mapList.get(i).get("start")+""+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+ startTime + "&nbsp;" +calendarName+"</a><br/>");
                            }else {
                                sbAmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+" data-startTime="+mapList.get(i).get("start")+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+ startTime + "&nbsp;" +calendarName+"</a><br/>");
                            }
                        } else {
                            if (calendarName.length()>20){
                                sbAmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+ " data-startTime="+mapList.get(i).get("start")+""+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+ startTime + "&nbsp;" +calendarName+"</a><br/>");
                            }else {
                                sbAmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+" data-startTime="+mapList.get(i).get("start")+""+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+ "&nbsp;" +calendarName+"</a><br/>");
                            }
                        }
                        map11.put(leaderId + "_name", sbAmCname); // 日程名称
                    } else if ("0".equals(isAmOrPm) && ("customCalendar".equals(selectViewType) || "subCalendar".equals(selectViewType) || "leaderCalendar".equals(selectViewType)) && leaderId.equals(calendarOwner)) { // 下午
                        /*2022018-判断领导日视图是否重要，重要则加标志*/
                        if("2".equals(mapList.get(i).get("degreeOfImportance"))){
                            sbPmCname.append("<span style=\"margin-right:4px\"><i class=\"iconfont icon-important text-red\"></i></span>");
                        }
                        // 开启上午/下午模式
                        if ("1".equals(leaderTimeSettingType)) {
                            if (calendarName.length()>20){
                                sbPmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+ " data-startTime="+mapList.get(i).get("start")+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+ startTime + "&nbsp;" +calendarName+"</a><br/>");
                            }else {
                                sbPmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+" data-startTime="+mapList.get(i).get("start")+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+ startTime + "&nbsp;" +calendarName+"</a><br/>");
                            }
                        }else {
                            if (calendarName.length()>20){
                                sbPmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+ " data-startTime="+mapList.get(i).get("start")+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                            }else {
                                sbPmCname.append("<a href=\"javascript:;\" data-leader=\""+leaderPartId+"\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+mapList.get(i).get("mainId")+""+" data-repeat="+mapList.get(i).get("repeat")+""+" data-startTime="+mapList.get(i).get("start")+" data-endTime="+mapList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                            }
                        }
                        map22.put(leaderId + "_name", sbPmCname); // 日程名称
                    }
                }
            }
            // 20220111 处理参与日程
            /*for (int j = 0; j < leaderIdList.size(); j++) {
                // 用户id
                String leaderId = leaderIdList.get(j);
                for (int i = 0; i < partMapList.size(); i++) {
                    Map<String, Object> map1 = partMapList.get(i);
                    String calendarName = map1.get("title") + "";
                    String secdatacode =  map1.get("secdatacode") + "";
                    String startTime = CalendarUtils.getTime(Integer.parseInt(map1.get("startTime")+""));
                    boolean isAllDay = (boolean) map1.get("allDay");
                    String amOrPm = StringUtils.null2String(map1.get("amOrPm"));
                    String isAmOrPm = StringUtils.null2String(map1.get("isAmOrPm"));

                    if("1".equals(amOrPm)){
                        if("1".equals(isAmOrPm)){
                            startTime = "9:00";
                        }else{
                            startTime = "14:00";
                        }
                    }

                    if(isAllDay){
                        startTime = "9:00";
                    }
                    if(StringUtils.isNotBlank(calendarName)){
                        calendarName.replaceAll("<", "&lt;");
                        calendarName.replaceAll(">", "&gt;");
                    }
                    String isComplate = "0";
                    List<String> partIdList = calendarFinishedDao.findPartId(map1.get("id") + "");
                    if (null!=partIdList&&partIdList.size()>0){
                        if (partIdList.contains(leaderId)){
                            isComplate = "1";
                        }
                    }
                    // 查询日程参与人员
                    String calendarId = String.valueOf(null==map1.get("id") ? "" : map1.get("id"));
                    Calendar one = this.findOne(calendarId);
                    List<String> scopeValueList = calendarDao.selectScopeValueList(one.getParticipant());
                    // 参与日程与人员匹配
                    if (null!=scopeValueList&&scopeValueList.size()>0) {
                        for (String scopeValue : scopeValueList) {
                            StringBuffer partAmCname = new StringBuffer();
                            // 开启上午/下午模式
                            if ("1".equals(leaderTimeSettingType)) {
                                if (calendarName.length()>20){
                                    partAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+map1.get("id")+""+" data-repeat="+map1.get("repeat")+""+ " data-startTime="+map1.get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    partAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+map1.get("id")+""+" data-repeat="+map1.get("repeat")+""+" data-startTime="+map1.get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            }else {
                                if (calendarName.length()>20){
                                    partAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+map1.get("id")+""+" data-repeat="+map1.get("repeat")+""+ " data-startTime="+map1.get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    partAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+map1.get("id")+""+" data-repeat="+map1.get("repeat")+""+" data-startTime="+map1.get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            }
                            // 上午
                            if ("1".equals(isAmOrPm)) {
                                if (scopeValue.equals(leaderId)) {
                                    String valueStr = String.valueOf(null == map11.get(one.getCalendarOwner() + "_name") ? "" : map11.get(one.getCalendarOwner() + "_name"));
                                    StringBuffer sb = new StringBuffer(valueStr);
                                    StringBuffer append = sb.append(partAmCname);
                                    map11.put(one.getCalendarOwner() + "_name", append); // 日程名称
                                }
                                // 下午
                            } else if ("0".equals(isAmOrPm)) {
                                if (scopeValue.equals(leaderId)) {
                                    String valueStr = String.valueOf(null == map22.get(one.getCalendarOwner() + "_name") ? "" : map22.get(one.getCalendarOwner() + "_name"));
                                    StringBuffer sb = new StringBuffer(valueStr);
                                    StringBuffer append = sb.append(partAmCname);
                                    map22.put(one.getCalendarOwner() + "_name", append); // 日程名称
                                }
                            }
                        }
                    }
                }
            }*/
            // 上午
            if (map11!=null&&map11.size()>0) {
                map11.put("isAmOrPm", "1");
                mapResult.add(map11);
            }
            // 下午
            if (map22!=null&&map22.size()>0) {
                map22.put("isAmOrPm", "0");
                mapResult.add(map22);
            }
            /****************************组装结果 end******************************/
        }else {
            //选择进行中或者已完成
            if (StringUtils.isNotEmpty(ingOrFinish)) {
                result = this.getOaCalendar(sharedId, userId, corpId, title, category, viewType, start, end, token, leader, ingOrFinish);
            } else {
                result = this.getOaCalendar(sharedId, userId, corpId, title, category, viewType, start, end, token, leader,user);
            }
            // 我的日程
            if (StringUtils.isNotBlank(myCalendar) && "1".equals(myCalendar)) {
                if (StringUtils.isNotBlank(result)) {
                    // json字符串转List<Map<String, Object>>
                    resultList = (List<Map<String, Object>>) JSONArray.parse(result);
                    CalendarUtils.replaceSpecial(resultList);
                    // 按照上午、下午降序排序
                    CalendarUtils.sortResultListByAmOrPm(resultList);

                }
            } else {
                // 共享日程
                if (StringUtils.isNotBlank(result)){
                    // json字符串转List<Map<String, Object>>
                    resultList = (List<Map<String, Object>>) JSONArray.parse(result);
                }
                CalendarUtils.replaceSpecial(resultList);
                // 按照start开始时间降序排序
                CalendarUtils.sortResultList(resultList,"startTime");

                /****************************组装结果 start******************************/
                // 共享id集合
                List<String>  leaderIdList= Arrays.asList(shareId.split(","));
                // 上午
                HashMap<String, Object> map11 = new HashMap<>();
                // 下午
                HashMap<String, Object> map22 = new HashMap<>();
                for (int j = 0; j < leaderIdList.size(); j++) {
                    // 日程所属人员id
                    String leaderId = leaderIdList.get(j);
                    // 上午-日程id
                    StringBuilder sbAmCid = new StringBuilder();
                    // 上午-日程名称
                    StringBuilder sbAmCname = new StringBuilder();
                    // 下午-日程id
                    StringBuilder sbPmCid = new StringBuilder();
                    // 下午-日程名称
                    StringBuilder sbPmCname = new StringBuilder();
                    for (int i = 0; i < resultList.size(); i++) {
                        // 获取日程所属人员id
                        String calendarOwner = resultList.get(i).get("calendarOwner") + "";
                        String calendarId = resultList.get(i).get("id") + "";
                        String calendarName = resultList.get(i).get("title") + "";
                        String secdatacode =  resultList.get(i).get("secdatacode") + "";
                        String startTime = CalendarUtils.getTime(Integer.valueOf(resultList.get(i).get("startTime")+""));

                        boolean isAllDay = (boolean) resultList.get(i).get("allDay");
                        String amOrPm = StringUtils.null2String(resultList.get(i).get("amOrPm"));
                        String isAmOrPm = StringUtils.null2String(resultList.get(i).get("isAmOrPm"));

                        if("1".equals(amOrPm)){
                            if("1".equals(isAmOrPm)){
                                startTime = "9:00";
                            }else{
                                startTime = "14:00";
                            }
                        }

                        if(isAllDay){
                            startTime = "";
                        }
                        if(StringUtils.isNotBlank(calendarName)){
                            calendarName = calendarName.replace("<", "&lt;").replace(">", "&gt;");
                        }
                        // 20210831 日程标记完成功能：判断当前用户是否完成指定日程
                        String isComplate = "0";
                        List<String> partIdList = calendarFinishedDao.findPartId(resultList.get(i).get("id") + "");
                        if (null!=partIdList&&partIdList.size()>0){
                            if (partIdList.contains(userId)){
                                isComplate = "1";
                            }
                        }
                        //songwy add 判断当前所属用户是否存在集合中
                        if (null!=partIdList&&partIdList.size()>0){
                            if (partIdList.contains(calendarOwner)){
                                isComplate = "1";
                            }
                        }
                        //songwy add end
                        if ("1".equals(resultList.get(i).get("isAmOrPm")) && leaderId.equals(calendarOwner)) { //上午
                            /*2022-01-19-共享日程日视图增加重要标志*/
                            if("2".equals(resultList.get(i).get("degreeOfImportance"))){
                                sbAmCname.append("<span style=\"margin-right:4px\"><i class=\"iconfont icon-important text-red\"></i></span>");
                            }
                            // 开启上午/下午模式
                            if ("1".equals(leaderTimeSettingType)){
                                if (calendarName.length()>20){
                                    sbAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+ " data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    sbAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+" data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            } else {
                                if (calendarName.length()>20){
                                    sbAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+ " data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+resultList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    sbAmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+" data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+resultList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            }
                            map11.put(leaderId + "_name", sbAmCname); // 日程名称
                        } else if ("0".equals(resultList.get(i).get("isAmOrPm")) && leaderId.equals(calendarOwner)) { // 下午
                            /*2022-01-19-共享日程日视图增加重要标志*/
                            if("2".equals(resultList.get(i).get("degreeOfImportance"))){
                                sbPmCname.append("<span style=\"margin-right:4px\"><i class=\"iconfont icon-important text-red\"></i></span>");
                            }
                            // 开启上午/下午模式
                            if ("1".equals(leaderTimeSettingType)){
                                if (calendarName.length()>20){
                                    sbPmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+ " data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    sbPmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+" data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+null+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            } else {
                                if (calendarName.length()>20){
                                    sbPmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" title="+calendarName+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+ " data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+resultList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }else {
                                    sbPmCname.append("<a href=\"javascript:;\" data-secdatacode="+secdatacode+" data-belong="+null+" data-category="+null+" data-isComplate="+isComplate+""+" data-id="+resultList.get(i).get("id")+""+" data-repeat="+resultList.get(i).get("repeat")+""+" data-startTime="+resultList.get(i).get("start")+""+" data-endTime="+resultList.get(i).get("end")+" onclick=\"tableCalendarView(this)\">"+startTime+"&nbsp;"+calendarName+"</a><br/>");
                                }
                            }
                            map22.put(leaderId + "_name", sbPmCname); // 日程名称
                        }
                    }
                }
                // 上午
                if (map11!=null && map11.size()>0) {
                    map11.put("isAmOrPm", "1");
                    mapResult.add(map11);
                }
                // 下午
                if (map22!=null && map22.size()>0) {
                    map22.put("isAmOrPm", "0");
                    mapResult.add(map22);
                }
                /****************************组装结果 end******************************/
            }
        }
        if (StringUtils.isNotBlank(myCalendar) && "1".equals(myCalendar)){
            // 我的日程-日视图数据
            return new PageImpl(resultList);
        } else {
            return new PageImpl(mapResult);
        }

    }

    /**
     * 获取领导数据(只有查看领导日程才有领导数据)
     * @param sharedId 共享id
     * @param corpId 单位id
     * @param title 查询标题
     * @param category 日程分类
     * @param start 查询开始时间
     * @param end 查询结束时间
     * @param token 身份信息
     * @param leader 1 领导日程
     * @param selectViewType 选择的哪个日程  我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar
     * @param viewType 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
     * @param userId 登录人id
     * @param ingOrFinish 选择了进行中、已完成
     *
     *
     */
    public List<Map<String,Object>> getOaOwnerInfoResult(String sharedId, String corpId, String title, String category, String start, String end, String token, String leader, String selectViewType,
                     String viewType, String userId, String ingOrFinish,WebUser user) throws ParseException {

        List<Map<String,Object>> map = new ArrayList<>();
        List<Map<String,Object>> mapResult = new ArrayList<>();

        try {
            String result = "";
            //如果是领导日程、下属日程
            if (StringUtils.isNotBlank(leader)) {
                result = this.getOaCalendarWithoutLeader("", sharedId, corpId, title, category, "calendar", start, end, token, leader,selectViewType);
                //领导日程，对参与人进行处理
                JSONArray ja = JSONArray.parseArray(result);
                List<Map<String,String>> resultListTem = JSONArray.toJavaObject(ja,List.class);
                resultListTem = this.changePartToLeaderName(resultListTem, sharedId, user.getCorpId(), user.getJwtToken(),"");
                result = JSONArray.toJSONString(resultListTem);
                // 非领导日程
            } else {
                //选择进行中或者已完成
                if(StringUtils.isNotEmpty(ingOrFinish)) {
                    result = this.getOaCalendar(sharedId, userId, corpId, title, category,viewType, start, end, token,leader,ingOrFinish);
                }else {
                    result = this.getOaCalendar(sharedId, userId, corpId, title, category,viewType, start, end, token,leader,user);
                }

            }


            // 组装结果
            if (StringUtils.isNotBlank(result)) {
                // json字符串转List<Map<String, Object>>
                map = (List<Map<String, Object>>) JSONArray.parse(result);
            }
            for (Map<String, Object> map1 : map) {
                HashMap<String, Object> hashMap = new HashMap<>();
                String calendarOwner = StringUtils.null2String(map1.get("calendarOwner"));
                if("1".equals(map1.get("isPart"))){
                    calendarOwner = StringUtils.null2String(map1.get("leader"));;
                }
                // id
                hashMap.put("calendarOwner", calendarOwner);
                // 名称
                hashMap.put("calendarOwnerName", calendarDao.findUserName(calendarOwner));
                mapResult.add(hashMap);
            }
            // 去重
            if (mapResult.size() > 0) {
                for (int i = 0; i < mapResult.size(); i++) {
                    Map<String, Object> map1 = mapResult.get(i);
                    for (int j = i + 1; j < mapResult.size(); j++) {
                        if (map1.get("calendarOwner").equals(mapResult.get(j).get("calendarOwner"))) {
                            mapResult.remove(j);
                            j--;
                        }
                    }
                }
            }

            return mapResult;
        }catch (Exception e){
            LOG.error("获取领导数据错误",e);
            return mapResult;
        }

    }

    /**
     * 获取日程列表，列表视图查询方法
     * @param start 搜索开始时间
     * @param end 搜索结束时间
     * @param leader 领导日程 1
     * @param pageable 分页参数
     * @param category 日程分类
     * @param sharedId 共享id
     * @param corpId 单位id
     * @param title 搜索内容
     * @param token 身份信息
     * @param userId 登录人id
     * @param viewType 查看类型 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
     * @param ingOrFinish 单选中 进行中、已完成
     * @return finalResult  List<Map<String, String>> 结果集
     *
     *
     */

    public List<Map<String, String>> getOaCalendarListResult(String start, String end, String leader, Pageable pageable, String category, String sharedId, String corpId, String title, String token,
                                             String userId, String viewType, String ingOrFinish){
        String[] dates = CalendarUtils.getMonthInTwoDate(start, end);
        List<Map<String, String>> result ;
        List<Map<String, String>> finalResult = new ArrayList<>();
        if (StringUtils.isNotBlank(leader) && StringUtils.equals(leader, "1")) {
            result = this.getOaCalendarList(pageable, "", category, sharedId, corpId, title, "calendar", dates[0], dates[1], token, userId, "leaderOrSubCalendar", "", "");

            result = this.changePartToLeaderName(result, sharedId, corpId,token,"");

        } else {
            result = this.getOaCalendarList(pageable, sharedId, category, userId, corpId, title, viewType, dates[0], dates[1], token, userId, "calendar", ingOrFinish, "");
        }
        //根据map中的startWeek字段进行排序
        if (CollectionUtils.isNotEmpty(result)) {
            // 获取所有start字段后去重排序
            List<String> startList = new ArrayList<>();
            for (Map<String, String> map : result) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if ("start".equals(entry.getKey())) {
                        startList.add(entry.getValue());
                    }
                }
            }
            // 去重
            HashSet hashSet = new HashSet(startList);
            startList.clear();
            startList.addAll(hashSet);
            // 时间排序
            CalendarUtils.sortListString(startList);

            // 获取与start值相同的
            for (String startVar : startList) {
                List<Map<String, String>> listVar = new ArrayList<>();
                for (Map<String, String> map : result) {
                    if (startVar.equals(map.get("start"))) {
                        listVar.add(map);
                    }
                }

                // 按照isAmOrPm排序
                CalendarUtils.sortResultListString(listVar,"isAmOrPm");


                finalResult.addAll(listVar);
            }
        }

        return finalResult;

    }

    /**
     * 对结果的参与日程的所有人替换成指定的人员信息
     * @param result 要修改的结果集
     * @param sharedId 指定的人员id串
     * @param corpId 单位Id
     * @param token 身份信息
     * @param selectViewType 选择的日程类型（处理pc端页面日历视图的标题）
     * @return
     *
     */
    public List<Map<String,String>> changePartToLeaderName(List<Map<String,String>> result, String sharedId, String corpId, String token, String selectViewType){
        List<String> userList = Arrays.asList(sharedId.split(","));
        List<Map<String,String>> partDataList = new ArrayList<>();
        List<Map<String,Object>> userMapList = userApiService.getUserList(sharedId, corpId, "", token);
        Map<String,Map<String,Object>> userIdForKeyMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(userMapList)){
            for(Map<String,Object> userMap : userMapList){
                userIdForKeyMap.put(userMap.get("id").toString(),userMap);
            }
        }
        String categoryName = "";
        String participant = "";
        Map<String,String> resultMap = new HashMap<>();
        boolean isCalendrView = false;

        //获取参与日程的日程分类
        CalendarCategory category = new CalendarCategory();
        List<CalendarCategory> categorys = this.calendarCategoryDao.getPartCategory(corpId);
        if (CollectionUtils.isNotEmpty(categorys)) {
            category = categorys.get(0);
        }

        for(int i=0; i<result.size(); i++){
            resultMap = result.get(i);

            //替换掉特殊字符
            String oldTitle = resultMap.get("title");
            if(StringUtils.isNotEmpty(oldTitle)){
                resultMap.put("title",oldTitle.replace("flexbracketB","[").replace("flexbracketE","]"));
            }

            String realTitle = resultMap.get("realTitle");
            if(StringUtils.isNotEmpty(realTitle)){
                resultMap.put("realTitle",realTitle.replace("flexbracketB","[").replace("flexbracketE","]"));
            }

            String content = resultMap.get("content");
            if(StringUtils.isNotEmpty(content)){
                resultMap.put("content",content.replace("flexbracketB","[").replace("flexbracketE","]"));
            }

            String address = resultMap.get("address");
            if(StringUtils.isNotEmpty(address)){
                resultMap.put("address",content.replace("flexbracketB","[").replace("flexbracketE","]"));
            }


            categoryName = resultMap.get("category");
            //日历视图处理
            if(StringUtils.isBlank(categoryName)){
                categoryName = resultMap.get("classfiyName");
                isCalendrView = true;
            }

            //对标题进行处理（自定义日程）
            if("customCalendar".equals(selectViewType) && !"参与日程".equals(categoryName)){
                String title = resultMap.get("title");
                title =userIdForKeyMap.get(resultMap.get("calendarOwner")).get("userName")+"-"+ title;
                resultMap.put("title",title);
            }

            if("参与日程".equals(categoryName)){
                participant = resultMap.get("participant2");

                if(StringUtils.isNotBlank(participant)){
                    List<String> scopeValueList = calendarDao.selectScopeValueList(participant);
                    //获取该日程下的完成情况
                    List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarId(resultMap.get("mainId")!=null?resultMap.get("mainId"):resultMap.get("id"));
                    String finishedIds = "";
                    //完成人id
                    if(CollectionUtils.isNotEmpty(calendarFinishedList)){
                        for(CalendarFinished calendarFinished : calendarFinishedList){
                            finishedIds = finishedIds+","+calendarFinished.getPartId();
                        }
                    }
                    if(finishedIds.length()>1){
                        finishedIds = finishedIds.substring(1);
                    }

                    for(String partUserId : userList){
                        if(scopeValueList.contains(partUserId)){
                            Map<String,String> resultNewMap = new HashMap<>();
                            resultNewMap.putAll(resultMap);
                            resultNewMap.put("owner",userIdForKeyMap.get(partUserId).get("userName").toString());
                            resultNewMap.put("leader",partUserId);
                            resultNewMap.put("orgNamePath",userIdForKeyMap.get(partUserId).get("orgNamePath").toString());
                            //领导日程下，名字得重新赋领导名字
                            if("leaderCalendar".equals(selectViewType)){
                                String title = userIdForKeyMap.get(partUserId).get("userName")+"-"+resultMap.get("title").split("-",2)[1];
                                resultNewMap.put("title",title);
                            }
                            if("customCalendar".equals(selectViewType)){
                                String title =userIdForKeyMap.get(partUserId).get("userName")+"-"+ resultMap.get("title");
                                resultNewMap.put("title",title);
                            }
                            //重复日程处理 重复日程、非主日程、且未操作
                            if("1".equals(resultMap.get("repeat"))){
                                //获取主日程数据，判断是否和map数据的时间一致，不一致是没有改过的子日程，不必处理
                                Calendar mainCalendar = this.findOne(resultMap.get("mainId")!=null?resultMap.get("mainId"):resultMap.get("id"));
                                String mapDateStr = resultMap.get("start").split("T")[0].substring(0,10);
                                String mainDateStr = DateUtils.formatDate(mainCalendar.getStartDate(),"yyyy-MM-dd");
                                //相等，是主日程
                                if(mainDateStr.equals(mapDateStr)){
                                    if(finishedIds.contains(partUserId)){
                                        if(isCalendrView){
                                            resultNewMap.put("isComplate","true");
                                        }else {
                                            resultNewMap.put("isComplate","1");
                                        }
                                        resultNewMap.put("color","#3f3f3f");
                                    }else{
                                        if(isCalendrView){
                                            resultNewMap.put("isComplate","false");
                                        }else {
                                            resultNewMap.put("isComplate","0");
                                        }
                                        //替换成本来的日程背景色(参与日程)
                                        resultNewMap.put("color",category.getBackColor());
                                    }
                                }
                            }else{
                                if(finishedIds.contains(partUserId)){
                                    if(isCalendrView){
                                        resultNewMap.put("isComplate","true");
                                    }else {
                                        resultNewMap.put("isComplate","1");
                                    }
                                    resultNewMap.put("color","#3f3f3f");
                                }else{
                                    if(isCalendrView){
                                        resultNewMap.put("isComplate","false");
                                    }else {
                                        resultNewMap.put("isComplate","0");
                                    }
                                    //替换成本来的日程背景色(参与日程)
                                    resultNewMap.put("color",category.getBackColor());
                                }
                            }


                            partDataList.add(resultNewMap);
                        }
                    }
                }else{
                    partDataList.add(resultMap);
                }

            }else{
                partDataList.add(resultMap);
            }
        }

        result = partDataList;
        return result;
    }


    /**
     * 查看日程
     * @param viewType -1 会议查看  其他，日程
     * @param corpId 单位id
     * @param id 日程数据id
     * @param token 身份信息
     * @param userId 用户Id
     * @param type 查看类型  view 查看 其他编辑
     * @param logLeader 日志类型
     * @param weekLeader 领导日志类型
     * @param leaderCateId 领导日程分类id
     * @param repeat 是否重复 1 重复日程
     * @param start 日程开始时间
     * @param end 日程结束时间
     * @param userLevel 用户密级
     * @param selectViewType 选择的哪个日程  我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar  其他日程 customCalendar
     *
     *
     */
    public Map<String, Object> viewCalendarInfo(String viewType, String corpId, String id, String token, String userId, String type, String logLeader, String weekLeader,
                                    String leaderCateId, String repeat, String start, String end, int userLevel, String selectViewType, String leaderId){

        Map<String, Object> map = new HashMap<>();
        Map<String, String> paramMap = new HashMap<String, String>();

        String mailSecdatacode = "";

        if("-1".equals(viewType)){//会议页面查看
            paramMap.put("corpId", corpId);
            paramMap.put("applyRecordId", id);
            paramMap.put("token", token);
            paramMap.put("userId", userId);
        }else {//日程页面查看
            Calendar calendar = this.findOne(id);
            //获取邮件数据的加密值
            Map encodeFileMap = new HashMap();
            encodeFileMap.put("id",calendar.getModuleDataId());
            encodeFileMap.put("userId",userId);
            Map<String,String> encodeMap = DealFieldEncodeUtils.dealDataMap(encodeFileMap,"id,userId","mail",null);
            mailSecdatacode = encodeMap.get("secdatacode");

            Map<String, Object> creater = this.userApiService.getUser(calendar.getCalendarOwner(), corpId, "", token);
            if(creater != null){
                //领导日程下，要显示领导的名称
                if("leaderCalendar".equals(selectViewType)){
                    //根据leaderCateId获取领导信息
                    Map<String,String> leaderCanViewMap = calendarLeaderSettingService.getViewerLeaderIdsByCategoryId(leaderCateId,userId,corpId,token,"");

                    List<String> leaderIdsList = leaderCanViewMap.keySet().stream().collect(Collectors.toList());

                    String leaderIds = String.join(",", leaderIdsList);

                    //此日程领导是参与人
                    if(!leaderIds.contains(calendar.getCalendarOwner())){
                        List<Map<String,Object>> userMapList = userApiService.getUserList(leaderIds, corpId, "", token);
                        Map<String,Map<String,Object>> userIdForKeyMap = new HashMap<>();
                        for(Map<String,Object> userMap : userMapList){
                            userIdForKeyMap.put(userMap.get("id").toString(),userMap);
                        }

                        String leaderNames = StringUtils.null2String(userIdForKeyMap.get(leaderId).get("userName"));

                        calendar.setCalendarOwnerName(leaderNames);
                    }else{
                        calendar.setCalendarOwnerName(StringUtils.null2String(creater.get("userName")));
                    }

                }else{
                    calendar.setCalendarOwnerName(StringUtils.null2String(creater.get("userName")));
                }
            }
            if(calendar == null){
                return map;
            }

            calendarSendMsgUtils.takeMsgDone(calendar, corpId, token, userId);

            // 20210831 日程标记完成功能
            List<String> partIdList = calendarFinishedDao.findPartId(calendar.getId());
            // 当前日程未全部标记完成
            if (!"1".equals(calendar.getIsComplate())){
                if (null!=partIdList&&partIdList.size()>0){
                    // 判断当前用户是否标记完成
                    if (partIdList.contains(userId)){
                        calendar.setIsComplate("1");
                    }
                } else {
                    calendar.setIsComplate("0");
                }
            }
            map.put("entity", calendar);
            //日程拥有者id
            String ownerId = calendar.getCalendarOwner();
            if("view".equals(type)){//查看日程
                if(StringUtils.isNoneBlank(logLeader)) {
                    if(StringUtils.equals(logLeader, "leader")) {
                        if(StringUtils.equals(weekLeader, "weekLeader")){

                            logService.saveModuleLog("calendar:weekLeader:03", calendar.getTitle(), "");
                        } else{

                            logService.saveModuleLog("calendar:leader:03", calendar.getTitle(), "");
                        }

                        Map<String, String> canEditLeaderMap = calendarLeaderSettingService.getLeaderIdsByUserIdAndCategoryId("", userId, "", corpId, leaderCateId, token);
                        String leaderName = "";
                        String partLeaderName = "";
                        if(MapUtils.isNotEmpty(canEditLeaderMap)) {
                            leaderName = canEditLeaderMap.get(ownerId);
                            partLeaderName = canEditLeaderMap.get(leaderId);
                        }
                        //领导日程判断是否可编辑
                        if(StringUtils.isNotEmpty(leaderName)) {
                            map.put("canEdit", "yes");
                        }else {
                            map.put("canEdit", "no");
                        }

                        //领导日程是否可标记完成
                        if(StringUtils.isNotEmpty(partLeaderName)) {
                            map.put("canCompalte", "yes");
                            map.put("leaderId",leaderId);
                        }else {
                            map.put("canCompalte", "no");
                        }

                    }else if(StringUtils.equals(logLeader, "sub")) {
                        if(StringUtils.equals(selectViewType, "customCalendar")){
                            logService.saveModuleLog("calendar:customCalendar:03", calendar.getTitle(), "");
                        }else{
                            logService.saveModuleLog("calendar:sub:03", calendar.getTitle(), "");
                        }

                    }else if(StringUtils.equals(selectViewType,"customCalendar")){
                        logService.saveModuleLog("calendar:customCalendar:03", calendar.getTitle(), "");
                    }
                }else {
                    if(StringUtils.equals(viewType, "share")){
                        //判断是否可编辑
                        String canEdit = this.judgeShareCanEdit(userId,calendar);
                        map.put("canEdit", canEdit);
                        logService.saveModuleLog("calendar:shareMe:03", calendar.getTitle(), "");
                    }else{
                        logService.saveModuleLog("calendar:mycalendar:03", calendar.getTitle(), "");
                    }

                }
                String startDate = "",endDate = "";
                String startCalendarDate = "";
                if("1".equals(repeat)){
                    startDate = start;
                    endDate = end;
                }else{
                    startDate = CalendarUtils.getStrByDate(calendar.getStartDate(), "yyyy-MM-dd");
                }
                String startDateNew = startDate;
                String endDateNew = endDate;
                startCalendarDate = startDate;
                startDate += " "+WEEKS[CalendarUtils.dayForWeek(startDate, "yyyy-MM-dd")-1];
                if("1".equals(calendar.getIsAllDay())||StringUtils.isNotBlank(calendar.getSetTimeFlag())){ //全天日程/上午/下午模式
                    endDate = startDate;
                    endDateNew = startDateNew;
                }else{
                    startDate += "  " + CalendarUtils.getTime(calendar.getStartTime());
                    startDateNew += " " + CalendarUtils.getTime(calendar.getStartTime());
                    if(!"1".equals(repeat)){
                        endDate = CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
                        endDateNew = CalendarUtils.getStrByDate(calendar.getEndDate(), "yyyy-MM-dd");
                    }
                    endDate += " "+WEEKS[CalendarUtils.dayForWeek(endDate, "yyyy-MM-dd")-1];
                    endDate += "  " + CalendarUtils.getTime(calendar.getEndTime());
                    endDateNew += " " + CalendarUtils.getTime(calendar.getEndTime());
                }
                map.put("startDateNew", startDateNew);//new字符串中不带星期几
                map.put("endDateNew", endDateNew);
                map.put("isAllDay", calendar.getIsAllDay());
                // 上午/下午模式中选中的值
                map.put("setTimeFlag", calendar.getSetTimeFlag());
                map.put("startDate", startDate);		//字符串中带星期几
                map.put("endDate", endDate);
                CalendarCategory category = this.calendarCategoryService.findOne(calendar.getCalendarCategory());
                map.put("cateName", category.getName());
                map.put("remind", calendar.getExpiryReminder());
                Map<String, String> textParams = new HashMap<>();
                textParams.put("corpId", corpId);

                String calendarStart = DateUtils.formatDate(calendar.getStartDate(),"yyyy-MM-dd");
                Map<String,String> partResultMap = this.judgeComplete(StringUtils.null2String(calendar.getParticipant()), calendar.getDuplicateType(), calendarStart, startCalendarDate, calendar.getId());

                map.put("partName", partResultMap.get("partName"));
                map.put("partComplateFlag", partResultMap.get("partComplateFlag"));
                String viewScope = this.popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "viewer", StringUtils.null2String(calendar.getViewer()));
                String viewConfigJson = this.userApiService.getScopeName(viewScope, corpId, token);
                map.put("viewName", viewConfigJson);
                String maintainScope = this.popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "maintainer", StringUtils.null2String(calendar.getMaintainer()));
                String maintainConfigJson = this.userApiService.getScopeName(maintainScope, corpId, token);
                map.put("maintainName", maintainConfigJson);
            }else{//编辑日程
                String startTime = "",endTime = "";
                if(!"1".equals(calendar.getIsAllDay())){
                    startTime = CalendarUtils.getTime(calendar.getStartTime());
                    endTime = CalendarUtils.getTime(calendar.getEndTime());
                }
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                String sharedId = "";
                Map<String, Object> map2 = new HashMap<>();
                if("share".equals(viewType)){
                    CalendarCategory category = this.calendarCategoryService.findOne(calendar.getCalendarCategory());
                    List<CalendarCategory> list = new ArrayList<>();
                    list.add(category);
                    map2 = this.calendarSettingService.getRemind(corpId,token);
                    map2.put("category", list);
                }else{
                    // 20210904 增加参数
                    map2 = this.calendarCategoryService.getCateAndRemind(viewType,"1",userId,sharedId,corpId,token,"", calendar.getCalendarCategory());
                }
                map.put("cateAndRemind", map2);
                String participant = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "participant", calendar.getParticipant());
                String viewer = "";
                if(StringUtils.isNotEmpty(calendar.getViewer())) {
                    viewer = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "viewer", calendar.getViewer());
                }
                String maintainer = "";
                if(StringUtils.isNotEmpty(calendar.getMaintainer())) {
                    maintainer = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "maintainer", calendar.getMaintainer());
                }
                Map<String, String> scope = new HashMap<>();
                scope.put("participant", participant);
                scope.put("viewer", viewer);
                scope.put("maintainer", maintainer);
                map.put("scope", scope);
            }
            //创建人
            if("share".equals(viewType)){
                String created = calendar.getCreatedBy();
                if("0".equals(calendar.getIsMain())){
                    Calendar mainCalendar = this.findOne(calendar.getBelongCalendar());
                    created = mainCalendar.getCreatedBy();
                }
                if("1".equals(created)){
                    map.put("creatorName", "系统管理员");
                }else{
                    Map<String,String> textParams = new HashMap<String,String>();
                    textParams.put("id",  created);
                    textParams.put("corpId", corpId);
                    List<Map> list = this.findUserName(created);
                    if(CollectionUtils.isNotEmpty(list)) {
                        map.put("creatorName", list.get(0).get("user_name"));
                    }
                }
            }else{
                if(userId.equals(calendar.getCreatedBy())) {
                    map.put("creatorName", "");
                }else if(userId.equals(calendar.getCalendarOwner())){
                    List<Map> list = this.findUserName(calendar.getCreatedBy());
                    if(CollectionUtils.isNotEmpty(list)) {
                        map.put("creatorName", list.get(0).get("user_name"));
                    }
                }else {
                    CalendarCategory category = calendarCategoryService.getCreatedName(calendar.getCalendarCategory(),corpId);
                    List<Map> list = this.findUserName(category.getCreatedBy());
                    if(CollectionUtils.isNotEmpty(list)) {
                        map.put("creatorName", list.get(0).get("user_name"));
                        map.put("join", "1");
                    }
                }
            }
            //附件
            String attachment = StringUtils.null2String(calendar.getAttachment());
            if(StringUtils.isNotBlank(attachment)){
                //如果环境涉密，对附件密级进行处理
                if(GlobalConstant.isUseSecretLevel()) {
                    //当前登录人可查看的附件
                    String newAttachment = "";
                    //当前登录人不可查看的附件，将不可查看的附件传到页面的隐藏域中，编辑保存时将编辑后的附件与不可查看的附件拼接成完整的附件id
                    String noEditAttachment = "";
                    String attachmentIds = attachment.replaceAll("\\|", ",");
                    //获取附件信息
                    List<Map<String, String>> attachmentList = this.attachmentUtilsService.getAttachmentInfos(attachmentIds, token);
                    //去除掉密级比当前查看人密级高的附件
                    for(Map<String,String> att : attachmentList) {
                        String secretLevel = String.valueOf(att.get("secretLevel"));
                        if(userLevel<=Integer.parseInt(secretLevel) || StringUtils.equals("0", secretLevel)) {
                            newAttachment += att.get("id")+"|";
                        }else {
                            noEditAttachment += att.get("id")+"|";
                        }
                    }
                    if(StringUtils.isNotBlank(newAttachment)) {
                        newAttachment = newAttachment.substring(0,newAttachment.length()-1);
                        String dataInitList = this.attachmentUtilsService.getAttachmentInfo(newAttachment,token);
                        map.put("attachment", "["+dataInitList+"]");
                    }else {
                        map.put("attachment", "[]");
                    }
                    map.put("noEditAttachment", noEditAttachment);
                }else {
                    String dataInitList = this.attachmentUtilsService.getAttachmentInfo(attachment,token);
                    map.put("attachment", "["+dataInitList+"]");
                    map.put("noEditAttachment", "");
                }
            }
        }
        //获取系统后台的消息设置(wxWork,ding,evoPortal)
        String reminderAction = "" ;
        Map<String, Object> appInfo = configService.getAppInfoByAppCode("calendar",corpId,token);
        if(MapUtils.isNotEmpty(appInfo)) {
            reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
        }
        String mobile = this.getSysParamValueByMark(corpId,token , "sysImType");
        String ifMobile = "0";
        if((mobile.contains("wxWork") || mobile.contains("ding") || mobile.contains("evoPortal") || mobile.contains("cocall") || mobile.contains("gding")) && reminderAction.contains("mobile") ) {
            ifMobile = "1";
        }

        String sms = StringUtils.equals(this.getSysParamValueByMark(corpId, token, "sysSMSsetting"), "1") && reminderAction.contains("sms") ? "1" : "0";
        map.put("sysImType",ifMobile);
        map.put("sysMailSetting","1");
        map.put("sysSMSsetting",sms);
        map.put("mailSecdatacode",mailSecdatacode);
        
        return map;
    }

    /**
     * 获取参与人日程完成情况
     * @param participant 参与人scope值
     * @param duplicateType 日程重复类型
     * @param calendarStart 实际日程开始时间（重复日程下，子日程实际时间和主日程时间不同）
     * @param startCalendarDate 页面显示的时间
     * @param calendarId 日程id
     * @return Map<String,String>  partName 完成人  partComplateFlag 完成情况 1 完成 0 未完成
     *
     */
    public Map<String,String> judgeComplete(String participant, String duplicateType, String calendarStart, String startCalendarDate, String calendarId){

        StringBuffer partConfigJson = new StringBuffer();
        StringBuffer complateFlag = new StringBuffer();

        boolean isComplateJudege = true;
        if(!"no".equals(duplicateType)){
            //重复日程下,没有标记过的子日程，主日程完成不代表子日程也是完成的
            if(StringUtils.isNotEmpty(calendarStart)) {
                if(!StringUtils.equals(calendarStart, startCalendarDate)) {
                    isComplateJudege = false;
                }
            }
        }

        String partScope = this.popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "participant", participant);
        if(StringUtils.isNotEmpty(partScope)) {
            String[] partScopeList = partScope.split(",");
            for(String partId :partScopeList) {
                // 20210830 日程标记取消功能：查询指定参与人日程是否标记完成
                String isComplateFlag = "0";

                if(isComplateJudege) {
                    List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedByCalendarIdAndPartId(calendarId, partId.substring(9));
                    if (CollectionUtils.isNotEmpty(calendarFinishedList) && calendarFinishedList.size()>0){
                        isComplateFlag = "1";
                    } else {
                        isComplateFlag = "0";
                    }
                }

                List<Map> partScopeName = this.findUserName(partId.substring(9));
                if(partScopeName!=null) {
                    if(StringUtils.equals(partId, partScopeList[partScopeList.length-1])) {
                        partConfigJson.append(partScopeName.get(0).get("user_name"));
                        complateFlag.append(isComplateFlag);
                    }else {
                        partConfigJson.append(partScopeName.get(0).get("user_name")).append(",");
                        complateFlag.append(isComplateFlag).append(",");
                    }
                }
            }
        }

        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("partName", partConfigJson+"");
        resultMap.put("partComplateFlag", complateFlag+"");
        return resultMap;

    }


    /**
     * 获取单个日程事件json
     * @param calendarId 日程id
     * @param viewType 查看类型 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
     * @param userId 用户id
     * @param corpId 单位id
     * @param token 身份信息
     * @param searchStart 开始时间
     * @param searchEnd 结束时间
     * @return json json字符串
     *
     */
    public String getEventDataResult(String calendarId, String viewType, String userId, String corpId, String token, String searchStart, String searchEnd){

        Calendar calendar = this.findOne(calendarId);
        List<String> maintainFieldValue = new ArrayList<>();
        Calendar mainCalendar ;
        String json = "[";


        /**  获取所有完成了的日程记录信息，并封装好数据格式 **/
        List<String> calendarIds = new ArrayList<>();
        calendarIds.add(calendarId);
        List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedsByCalendarIds(calendarIds);
        Map<String,List<String>> partFinishedMap = new HashMap<>();
        List<String> partIdList = new ArrayList<>();
        for(CalendarFinished calendarFinished : calendarFinishedList){
            if(calendarId.equals(calendarFinished.getCalendarId())){
                partIdList.add(calendarFinished.getPartId());
            }
        }
        partFinishedMap.put(calendarId,partIdList);

        if(calendar != null){
            if("0".equals(calendar.getIsMain())){
                mainCalendar = this.findOne(calendar.getBelongCalendar());
            }else{
                mainCalendar = calendar;
            }
            boolean flag = true;
            if("share".equals(viewType)){
                flag = this.isView(mainCalendar, userId, corpId, token);
                maintainFieldValue = this.getMaintainFieldValue(userId,calendar.getCalendarOwner(),corpId,token);//维护日程
            }
            List<CalendarDelete> deletes = this.findByBelong(calendar.getId(), DateUtils.parseDate(searchEnd,"yyyy-MM-dd"));
            Map<String,List<CalendarDelete>> deletesMap = new HashMap<String,List<CalendarDelete>>();
            deletesMap.put(calendar.getId(), deletes);
            CalendarCategory category = this.findCategory(calendar.getCalendarCategory(),corpId);
            Map<String,CalendarCategory> categoryMap = new HashMap<String,CalendarCategory>();
            categoryMap.put(calendar.getCalendarCategory(), category);
            Map<String,List<Calendar>> repeatsMap = new HashMap<String,List<Calendar>>();
            List<Calendar> repeats = this.findCalendarByBelong(calendar.getId(), DateUtils.parseDate(searchStart,"yyyy-MM-dd"), DateUtils.parseDate(searchEnd,"yyyy-MM-dd"));
            repeatsMap.put(calendar.getId(), repeats);
            if(flag){
                json += this.getCalendarInfo("4","",mainCalendar, searchStart, searchEnd, viewType, userId, corpId, maintainFieldValue, deletesMap, categoryMap, repeatsMap,partFinishedMap);
                if(!"no".equals(mainCalendar.getDuplicateType())){//重复日程
                    List<Calendar> list = this.getCalendarByBelong(mainCalendar.getId(), searchStart, searchEnd);
                    if(!list.isEmpty()){
                        for(int i=0;i<list.size();i++){
                            Calendar cale = list.get(i);
                            flag = true;
                            if("share".equals(viewType)){
                                flag = this.isView(cale, userId, corpId, token);
                            }
                            if(flag){
                                json += "," + this.getCalendarInfo("4","",cale, searchStart, searchEnd, viewType, userId, corpId, maintainFieldValue, deletesMap, categoryMap, repeatsMap,partFinishedMap);
                            }
                        }
                    }
                }
            }else{
                flag = this.isView(calendar, userId, corpId, token);
                if(flag){
                    json += this.getCalendarInfo("4","",calendar, searchStart, searchEnd, viewType, userId, corpId, maintainFieldValue, deletesMap, categoryMap, repeatsMap,partFinishedMap);
                }
            }
        }

        json = json+"]";

        return json;
    }

    /**
     * 编辑、修改日程 消息推送方法
     *
     */
    public void editOrAddSendMessage(String jsonPart, Calendar entity, HttpServletRequest request, String userId, String corpId, String token, String allDay){

        // 是否设置上午/下午
        String leaderTimeSettingType = StringUtils.null2String(request.getParameter("leaderTimeSettingType"));

        try {
            if (StringUtils.isNotBlank(jsonPart)) {
                List<Map<String, String>> list = (List<Map<String, String>>) JSONArray.parse(jsonPart);
                String ids = "";
                for(Map<String,String> map : list){
                    ids += map.get("scopeValue") + ",";
                }
                ids = ids.substring(0, ids.length()-1);
                //所属人信息
                Map<String,Object> userMap =
                        userApiService.getUser(entity.getCalendarOwner(),corpId,"",token);
                CalendarCategory calendarCategory = calendarCategoryService.findOne(entity.getCalendarCategory());

                String start = "";
                String end = "";
                //是否是全天日程或已设置上午/下午
                if ("1".equals(allDay) || StringUtils.isNotBlank(leaderTimeSettingType)) {
                    //全天日程 开始结束相同
                    start = DateUtils.formatDate(entity.getStartDate(),DateUtils.DEFAULT_DATE_FORMAT);
                    end = start;
                }else{
                    //不是全天日程    精确到分
                    java.util.Calendar ca = java.util.Calendar.getInstance();
                    ca.setTime(entity.getStartDate());
                    ca.add(java.util.Calendar.SECOND,entity.getStartTime());
                    start = DateUtils.formatDate(ca.getTime(),DateUtils.SHORT_TIME_FORMAT);
                    ca.setTime(entity.getEndDate());
                    ca.add(java.util.Calendar.SECOND, entity.getEndTime());
                    end = DateUtils.formatDate(ca.getTime(),DateUtils.SHORT_TIME_FORMAT);
                }
                Map<String, String> paramMapApp = new HashMap<>();
                String repeat = "1";
                if ("no".equals(entity.getDuplicateType())) {
                    repeat = "0";
                }
                String columnValue = this.calendarSettingService.getCalendarColumn();
                paramMapApp.put("columnValue", columnValue);
                paramMapApp.put("isEdit","0");
                paramMapApp.put("repeat",repeat);
                paramMapApp.put("dataId", entity.getId());
                paramMapApp.put("name",StringUtils.null2String(userMap.get("userName")));
                paramMapApp.put("cateName", calendarCategory.getName());
                paramMapApp.put("title", entity.getTitle());
                paramMapApp.put("address", entity.getAddress());
                paramMapApp.put("start", start);
                paramMapApp.put("end", end);
                paramMapApp.put("sendPath",this.getSysImType(corpId,token));
                paramMapApp.put("remindStyle", entity.getRemindStyle());
                paramMapApp.put("ids", ids);
                paramMapApp.put("userId", userId);

                SendMessageDTO sendMessageDTO1 = new SendMessageDTO();
                SendMessageDTO sendMessageDTO2 = new SendMessageDTO();
                sendMessageDTO1.setModuleCode("calendar");
                sendMessageDTO2.setModuleCode("calendar");
                List<MessageBodyDTO> msgBodys1 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"umc","0");
                List<MessageBodyDTO> msgBodys2 = calendarSendMsgUtils.getMsgBodys(request, paramMapApp, corpId, token,"mobile","0");
                sendMessageDTO1.setMsgBodys(msgBodys1);
                sendMessageDTO2.setMsgBodys(msgBodys2);
                List<String> msgTypes1 = new ArrayList<String>();
                List<String> msgTypes2 = new ArrayList<String>();
                msgTypes1.add("umc");
                msgTypes1.add("sms");
                msgTypes2.add("mobile");
                sendMessageDTO1.setMsgTypes(msgTypes1);
                sendMessageDTO1.setCorpId(corpId);
                sendMessageDTO1.setToken(token);
                sendMessageDTO1.setResourceType(ResourceTypes.SYSTEM.getCode());
                sendMessageApiService.sendMessage(sendMessageDTO1);
                sendMessageDTO2.setMsgTypes(msgTypes2);
                sendMessageDTO2.setCorpId(corpId);
                sendMessageDTO2.setToken(token);
                sendMessageDTO2.setResourceType(ResourceTypes.SYSTEM.getCode());
                sendMessageApiService.sendMessage(sendMessageDTO2);
            }
        } catch (Exception e) {
            LOG.error("消息推送失败",e);
        }
    }

    /**
     * 判断给定的用户是否完成给定的日程
     * @param  calendarId  日程id
     * @param userId 用户id
     * @return isComplete boolean值， true表示 给定的用户已经完成给定的日程  false 表示该用户没有完成这个日程
     *
     */
    public boolean checkComplete(String calendarId, String userId){
        List<CalendarFinished> calendarFinishedList = calendarFinishedDao.findCalendarFinishedByCalendarIdAndPartId(calendarId,userId);
        boolean isComplete = false;
        if(CollectionUtils.isNotEmpty(calendarFinishedList)){
            isComplete = true;
        }

        return isComplete;
    }

    /**
     * 验证参数合法性
     *
     */
    public void verifyCalendarParameter(String parameter){
        if(!ValidateUtils.validateSql(parameter)){
            throw new ValidationException("非法参数");
        }

    }

    /**
     * 验证参数合法性
     *
     */
    public void verifySaveCalendar(HttpServletRequest request){
        //标题
        String title = request.getParameter("title");
        //验证是否有Sql语句注入
        if(!ValidateUtils.validateSql(title)){
            throw new ValidationException("非法参数");
        }

        String calendarCategory = request.getParameter("calendarCategory");
        //验证是否是id
        if(!ValidateUtils.validateId(calendarCategory)){
            throw new ValidationException("非法参数");
        }

        String settingId = request.getParameter("settingId");
        //验证特殊字符
        if(!ValidateUtils.validateId(settingId)){
            throw new ValidationException("非法参数");
        }

        String isAllDay = request.getParameter("isAllDay");
        //整数校验
        if(!ValidateUtils.validateInt(isAllDay)){
            throw new ValidationException("非法参数");
        }

        if(!ValidateUtils.validateComm(isAllDay)){
            throw new ValidationException("非法参数");
        }

        String startDateAll = request.getParameter("startDateAll");
        if(!ValidateUtils.validateSql(startDateAll)){
            throw new ValidationException("非法参数");
        }

        String startDate = request.getParameter("startDate");
        if(!ValidateUtils.validateSql(startDate) || !ValidateUtils.validateComm(startDate)){
            throw new ValidationException("非法参数");
        }

        String setTimeFlag = request.getParameter("setTimeFlag");
        if(setTimeFlag!=null && !ValidateUtils.validateInt(setTimeFlag)){
            throw new ValidationException("非法参数");
        }

        String endDate = request.getParameter("endDate");
        if(!ValidateUtils.validateSql(endDate) || !ValidateUtils.validateComm(endDate)){
            throw new ValidationException("非法参数");
        }

        String endTimeStr = request.getParameter("endTimeStr");
        if(!ValidateUtils.validateSql(endTimeStr) || !ValidateUtils.validateComm(endTimeStr)){
            throw new ValidationException("非法参数");
        }

        String startTimeStr = request.getParameter("startTimeStr");
        if(!ValidateUtils.validateSql(startTimeStr) || !ValidateUtils.validateComm(startTimeStr)){
            throw new ValidationException("非法参数");
        }

        String degreeOfImportance = request.getParameter("degreeOfImportance");
        if(degreeOfImportance!=null && !ValidateUtils.validateInt(degreeOfImportance)){
            throw new ValidationException("非法参数");
        }

        String content = request.getParameter("content");
        if(!ValidateUtils.validateSql(content)){
            throw new ValidationException("非法参数");
        }

        String partScope = request.getParameter("partScope");
        if(!ValidateUtils.validateSql(partScope)){
            throw new ValidationException("非法参数");
        }

        String jsonStrPart = request.getParameter("jsonStrPart");
        if(!CalendarUtils.verifyScopeStr(jsonStrPart)){
            throw new ValidationException("非法参数");
        }

        String jsonStrPartIds = request.getParameter("jsonStrPartIds");
        if(!ValidateUtils.validateSql(jsonStrPartIds)){
            throw new ValidationException("非法参数");
        }

        String address = request.getParameter("address");
        if(!ValidateUtils.validateSql(address)){
            throw new ValidationException("非法参数");
        }

        String duplicateTypeOne = request.getParameter("duplicateTypeOne");
        if(!ValidateUtils.validateSql(duplicateTypeOne)){
            throw new ValidationException("非法参数");
        }

        String duplicateType = request.getParameter("duplicateType");
        if(!ValidateUtils.validateSql(duplicateType)){
            throw new ValidationException("非法参数");
        }

        String duplicateTypeTwo = request.getParameter("duplicateTypeTwo");
        if(!ValidateUtils.validateSql(duplicateTypeTwo)){
            throw new ValidationException("非法参数");
        }

        String duplicateInterval = request.getParameter("duplicateInterval");
        if(!ValidateUtils.validateSql(duplicateInterval) || !ValidateUtils.validateComm(duplicateInterval)){
            throw new ValidationException("非法参数");
        }

        String weekSelectValue = request.getParameter("weekSelectValue");
        if(!ValidateUtils.validateSql(weekSelectValue)){
            throw new ValidationException("非法参数");
        }

        String monthSelectValue = request.getParameter("monthSelectValue");
        if(!ValidateUtils.validateSql(monthSelectValue)){
            throw new ValidationException("非法参数");
        }

        String duplicateEndType = request.getParameter("duplicateEndType");
        if(!ValidateUtils.validateSql(duplicateEndType) || !ValidateUtils.validateComm(duplicateEndType)){
            throw new ValidationException("非法参数");
        }

        String duplicateEndTypeValue = request.getParameter("duplicateEndTypeValue");
        if(!ValidateUtils.validateSql(duplicateEndTypeValue)){
            throw new ValidationException("非法参数");
        }

        String expiryReminder = request.getParameter("expiryReminder");
        if(!ValidateUtils.validateSql(expiryReminder)){
            throw new ValidationException("非法参数");
        }
        if(!ValidateUtils.validateParam(expiryReminder)){
            throw new ValidationException("非法参数");
        }

        String expiryReminderTime = request.getParameter("expiryReminderTime");
        if(!ValidateUtils.validateSql(expiryReminderTime)){
            throw new ValidationException("非法参数");
        }

        String remindStyle = request.getParameter("remindStyle");
        if(!ValidateUtils.validateSql(remindStyle) || !ValidateUtils.validateComm(remindStyle)){
            throw new ValidationException("非法参数");
        }

        String file = request.getParameter("file");
        if(!ValidateUtils.validateSql(file)){
            throw new ValidationException("非法参数");
        }

        String attachment = request.getParameter("attachment");
        if(!ValidateUtils.validateSql(attachment)){
            throw new ValidationException("非法参数");
        }

        String viewerScope = request.getParameter("viewerScope");
        if(!ValidateUtils.validateSql(viewerScope)){
            throw new ValidationException("非法参数");
        }

        String jsonStrViewer = request.getParameter("jsonStrViewer");
        if(!CalendarUtils.verifyScopeStr(jsonStrViewer)){
            throw new ValidationException("非法参数");
        }

        String jsonStrViewerIds = request.getParameter("jsonStrViewerIds");
        if(!ValidateUtils.validateSql(jsonStrViewerIds) || !ValidateUtils.validateComm(jsonStrViewerIds)){
            throw new ValidationException("非法参数");
        }

        String maintainerScope = request.getParameter("maintainerScope");
        if(!ValidateUtils.validateSql(maintainerScope)){
            throw new ValidationException("非法参数");
        }

        String jsonStrMaintainer = request.getParameter("jsonStrMaintainer");
        if(!CalendarUtils.verifyScopeStr(jsonStrMaintainer)){
            throw new ValidationException("非法参数");
        }

        String jsonStrMaintainerIds = request.getParameter("jsonStrMaintainerIds");
        if(!ValidateUtils.validateSql(jsonStrMaintainerIds)){
            throw new ValidationException("非法参数");
        }

        String id = request.getParameter("id");
        if(!ValidateUtils.validateId(id)){
            throw new ValidationException("非法参数");
        }

        String eventDate = request.getParameter("eventDate");
        if(!ValidateUtils.validateSql(eventDate)){
            throw new ValidationException("非法参数");
        }

        String updateType = request.getParameter("updateType");
        if(!ValidateUtils.validateSql(updateType) || !ValidateUtils.validateComm(updateType)){
            throw new ValidationException("非法参数");
        }

        String updateStartDate = request.getParameter("updateStartDate");
        if(!ValidateUtils.validateSql(updateStartDate)){
            throw new ValidationException("非法参数");
        }

        String updateEndDate = request.getParameter("updateEndDate");
        if(!ValidateUtils.validateSql(updateEndDate) || !ValidateUtils.validateComm(updateEndDate) ){
            throw new ValidationException("非法参数");
        }

        String syncModule = request.getParameter("syncModule");
        if(!ValidateUtils.validateSql(syncModule)){
            throw new ValidationException("非法参数");
        }

        String moduleDataId = request.getParameter("moduleDataId");
        if(!ValidateUtils.validateId(moduleDataId)){
            throw new ValidationException("非法参数");
        }

        String logLeader = request.getParameter("logLeader");
        if(!ValidateUtils.validateSql(logLeader)){
            throw new ValidationException("非法参数");
        }

        String viewType2 = request.getParameter("viewType2");
        if(!ValidateUtils.validateSql(viewType2)){
            throw new ValidationException("非法参数");
        }

        String leaderUserId = request.getParameter("leaderUserId");
        if(!ValidateUtils.validateSql(leaderUserId) || !ValidateUtils.validateComm(leaderUserId)){
            throw new ValidationException("非法参数");
        }

        if(!ValidateUtils.validateComm(leaderUserId)){
            throw new ValidationException("非法参数");
        }

        String noEditAttachment = request.getParameter("noEditAttachment");
        if(!ValidateUtils.validateSql(noEditAttachment)){
            throw new ValidationException("非法参数");
        }

        String leaderTimeSettingType = request.getParameter("leaderTimeSettingType");
        if(!ValidateUtils.validateSql(leaderTimeSettingType)){
            throw new ValidationException("非法参数");
        }

        String secdatacode = request.getParameter("secdatacode");
        if(!ValidateUtils.validateSql(secdatacode) || !ValidateUtils.validateComm(secdatacode)){
            throw new ValidationException("非法参数");
        }


    }


    /**
     * 日程数据新增到evoportal
     *
     */
    public void calendarSaveOrUpdateToEvoPortal(Calendar calendar,String corpId, String token){
        if(calendar==null || calendar.getId()==null){
            LOG.error("数据为空");
            return;
        }
        //20241031gaoyw日程同步到辽政通-s
        //Map<String,String> evoPortalUrlMap = calendarSettingService.getCalendarSettingValue(corpId,"evoPortalUrl");
        //String url = StringUtils.null2String(evoPortalUrlMap.get("evoPortalUrl"));
        String url = GlobalConstant.getConfig("app.lzt.url");
        //20241031gaoyw日程同步到辽政通-e
        if(StringUtils.isEmpty(url)){
            LOG.error("未配置同步url连接");
            return ;
        }

        CalendarThird calendarThird = calendarThirdService.getCalendarThird(calendar.getId(),"evoPortal");
        String dutyId = "";
        if(calendarThird != null && StringUtils.isNotEmpty(calendarThird.getThirdId())){
            dutyId = calendarThird.getThirdId();
        }else{
            calendarThird = new CalendarThird();
        }

        //获取人员map
        String partScope = this.popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "participant", calendar.getParticipant());
        if(StringUtils.isEmpty(partScope) || partScope.length()<1){
            partScope = calendar.getCalendarOwner();
        }else{
            partScope = partScope.replace("userSCOPE","");
            partScope = calendar.getCalendarOwner()+","+partScope;
        }
        List<Map<String,Object>> userList = userApiService.getUserList(partScope, corpId, "", token);
        List<Map<String,Object>> userInfoList = new ArrayList();
        List<String> receiverIdsList = new ArrayList();
        String thirdUserName = "";
        String thirdUserId = "";
        for(Map<String,Object> partUser : userList) {
            Map<String,Object> userMap = new HashMap<>();
            String evoPortalUserId = this.getEvoPortalUserId(StringUtils.null2String(partUser.get("id")),token,corpId);
            /*if(calendar.getCalendarOwner().equals(partUser.get("id"))){
                thirdUserName = StringUtils.null2String(partUser.get("userName"));
                thirdUserId = evoPortalUserId;
            }*/
            if(evoPortalUserId.length()>0){
                thirdUserId = evoPortalUserId;
            }
            userMap.put("id",evoPortalUserId);
            userMap.put("name",partUser.get("userName"));
            userMap.put("type","1");
            userInfoList.add(userMap);
            receiverIdsList.add(evoPortalUserId);
        }


        Map<String,Object> dataMap = new HashMap<>();
        //创建人  需要更改
        dataMap.put("creatorId",thirdUserId);
        //创建人姓名  可能需要更改
        dataMap.put("creatorName",thirdUserName);
        //主题
        dataMap.put("topic",calendar.getTitle());
        //地址
        dataMap.put("location",calendar.getAddress());
        //内容
        dataMap.put("content",calendar.getContent());
        dataMap.put("receiverIds",receiverIdsList.toArray());//日程接收人员的 ID 包含participant 中的所有人员
        //提醒时间
        if("punctuality".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","0");
        }else if("5min".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","5");
        }else if("10min".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","10");
        }else if("30min".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","30");
        }else if("1hour".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","60");
        }else if("3hour".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","180");
        }else if("6hour".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","360");
        }else if("1day".equals(calendar.getExpiryReminderTime())){
            dataMap.put("remind","1440");
        }else{
            dataMap.put("remind","-1");
        }


        //时间处理
        String startDate = DateUtils.formatDate(calendar.getStartDate(),"yyyy-MM-dd");
        String startTime = CalendarUtils.getTime(calendar.getStartTime())+":00";

        String endDate;
        String endTime;

        if("1".equals(calendar.getIsAllDay())){
            endDate = startDate;
            startTime = "00:00:00";
            endTime = "23:59:59";
        }else{
            endDate = DateUtils.formatDate(calendar.getEndDate(),"yyyy-MM-dd");
            endTime = CalendarUtils.getTime(calendar.getEndTime())+":00";
        }

        //开始时间
        dataMap.put("startTime",startDate+" "+startTime);
        //结束时间
        dataMap.put("endTime",endDate+" "+endTime);
        //参与人
        dataMap.put("participant",userInfoList);

        //20241031gaoyw日程同步到辽政通-s
        /*if(StringUtils.isEmpty(dutyId)){
            //从配置中读取url
            url = url+"/create";
        }else{
            //从配置中读取url
            url = url+"/modify/"+dutyId;
        }*/
        //20241031gaoyw日程同步到辽政通-e

        //输出同步的日程信息
        LOG.error("输出同步的日程信息："+JSON.toJSONString(dataMap));
        LOG.error("调用了接口："+url);
        //调用接口保存并接收返回值
        JSONObject jsonObject = null;
        try {
            //20241031gaoyw日程同步到辽政通-s
            String accssToken=getAccessToken();//获取token
            jsonObject = CalendarUtils.httpPost(url+"/api/schedule?access_token="+accssToken,dataMap);
            //jsonObject = CalendarUtils.httpPost(url,dataMap);
            //20241031gaoyw日程同步到辽政通-e
            //再强行试三次
            if(jsonObject==null){
                int i=0;
                do{
                    jsonObject = CalendarUtils.httpPost(url,dataMap);
                    i=i+1;
                    LOG.error("第"+i+"次重试！");
                }while(i<3&&jsonObject==null);
            }
            if(jsonObject==null){
                LOG.error("日程Id"+calendar.getId()+"同步失败");
                return;
            }
        } catch (Exception e) {
            LOG.error("日程Id"+calendar.getId()+"同步失败");
            return;
        }
        LOG.error("返回的同步信息："+JSON.toJSONString(jsonObject));
        //20241031gaoyw日程同步辽政通修改返回值
        String code = jsonObject.get("code")+"";
        if(code.equals("200")){
            //新建
            if(StringUtils.isEmpty(dutyId)){
                dutyId = jsonObject.getJSONObject("data").get("id")+"";
                if(StringUtils.isEmpty(dutyId)){
                    LOG.error("日程Id"+calendar.getId()+"同步失败");
                }else{
                    calendarThird.setCalendarId(calendar.getId());
                    calendarThird.setModuleCode("evoPortal");
                    calendarThird.setThirdId(dutyId);
                    calendarThird.setStatusMsg("同步成功");
                    calendarThirdService.save(calendarThird);
                }
            }else{
                //修改
                calendarThird.setStatusMsg("修改成功");
                calendarThirdService.save(calendarThird);
            }

        }else{
            LOG.error("日程Id"+calendar.getId()+"同步失败");
        }

    }


    /**
     *
     * evo同步删除日程数据
     *
     */
    public void calendarDeleteToEvoPortal(Calendar calendar,String corpId){
        CalendarThird calendarThird = calendarThirdService.getCalendarThird(calendar.getId(),"evoPortal");
        if(calendarThird==null || StringUtils.isEmpty(calendarThird.getThirdId())){
            LOG.error("日程"+calendar.getId()+"对应的evoPortal数据不存在");
            return;
        }else{
            //20241031gaoyw日程同步到辽政通-s
            String url = GlobalConstant.getConfig("app.lzt.url");
            //Map<String,String> evoPortalUrlMap = calendarSettingService.getCalendarSettingValue(corpId,"evoPortalUrl");
            //String url = StringUtils.null2String(evoPortalUrlMap.get("evoPortalUrl"));
            //20241031gaoyw日程同步到辽政通-s
            if(StringUtils.isEmpty(url)){
                LOG.error("未配置同步url连接");
            }

            JSONObject jsonObject = null;
            try {
                //20241031gaoyw日程同步到辽政通-s
                //jsonObject = CalendarUtils.httpPost(url+"/delete/"+calendarThird.getThirdId(),null);
                String accssToken=getAccessToken();//获取token
                jsonObject = CalendarUtils.doDel(url+"/api/schedule/"+calendarThird.getThirdId()+"?access_token="+accssToken);
                //20241031gaoyw日程同步到辽政通-e
                //再强行试三次
                if(jsonObject==null){
                    int i=0;
                    do{
                        jsonObject = CalendarUtils.httpPost(url,null);
                        i=i+1;
                    }while(i<3&&jsonObject==null);
                }
                if(jsonObject==null){
                    LOG.error("日程Id"+calendar.getId()+"删除失败");
                }
                //20241031gaoyw修改日程同步辽政通返回值
                String decode =jsonObject.get("code")+"";
                if(decode.equals("200")){
                    calendarThirdService.delete(calendarThird);
                }else{
                    LOG.error("日程Id"+calendar.getId()+"删除失败");
                }

            } catch (Exception e) {
                LOG.error("日程Id"+calendar.getId()+"删除失败");
            }
        }
    }

    /**
     * 将本地用户id转换为evoportal的用户id
     *
     */
    public String getEvoPortalUserId(String userId,String token,String corpId){
        /*String evoPortalUserId = "";
        Map<String, String> userTextParams = new HashMap<String, String>();
        userTextParams.put("id", userId);
        userTextParams.put("corpId", corpId);

        Map<String, Object> user = userApiService.getUser(userId, corpId, "", token);
        if(user!=null && user.size()>0) {
            evoPortalUserId = StringUtils.null2String(user.get("mhUId"));
        }

        return evoPortalUserId;*/
        String evoPortalUserId = "";
        String fwsql=" select  uuid from sys_user where id=? " ;
        List<Map<String, Object>> fwlist = this.jdbcTemplate.queryForList(fwsql,new Object[] {userId});
        for (Map map : fwlist) {
            evoPortalUserId = map.get("uuid")+"";
        }
        return evoPortalUserId;
    }

    /**
     * 领导日程导入
     *
     */
    public OperationResult insertData(List<LeadarCalendarDto> leadarCalendararList, HttpServletRequest request) {

        if(CollectionUtils.isEmpty(leadarCalendararList)){
            return OperationResult.buildFailureResult("无导入数据！");
        }

//        Pattern pattern = Pattern.compile("^([\\u4E00-\\u9FA5]|\\w|\\>|\\/|\\.|\\·|\\~|\\@|\\（|\\—|\\）|\\(|\\)|\\-|\\－|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\。|\\、|\\《|\\》|\\；|\\:|\\;|\\？|\\\"|\\”|\\“|\\?)*([\\u4E00-\\u9FA5]|\\w|\\>|\\/|\\.|\\·|\\~|\\@| |\\（|\\\"|\\”|\\“|\\）|\\(|\\)|\\-|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\。|\\、|\\—|\\《|\\》|\\；|\\：|\\;|\\？|\\?)*([\\u4E00-\\u9FA5]|\\w|\\/|\\>|\\.|\\·|\\~|\\@|\\（|\\）|\\(|\\)|\\-|\\－|\\+|\\=|\\{|\\}|\\【|\\】|\\[|\\]|\\\"|\\”|\\“|\\。|\\、|\\《|\\》|\\；|\\：|\\;|\\？|\\—|\\?)+$");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        GregorianCalendar generalCalendar = new GregorianCalendar();

        //当前登陆人
        WebUser user = WebUtils.getCurrentUser();
        String userId = user.getUserId();
        String corpId = user.getCorpId();
        String token = user.getJwtToken();

        //获取当前登陆人可新建日程的领导
        List<Map> canEditLeaderList = calendarLeaderSettingService.getCanEditLeaderInfo(userId,corpId);
        if(CollectionUtils.isEmpty(canEditLeaderList)){
            return OperationResult.buildFailureResult("无可维护领导！");
        }

        //获取提醒设置
        String remindStyle = this.getCalendarRemind(corpId,token);

        //获取基础设置
        Map<String,String> settingMap = calendarSettingService.getCanlenderFieldSetting(corpId);
        String leaderTimeSettingType = settingMap.get("leaderTimeSettingType");

        Map<String,String> canEditLeaderMap = this.getCanEditLeaderMap(canEditLeaderList);

        List<Calendar> calendarList = new ArrayList<>();

        int listSize = leadarCalendararList.size();
        for(int i=0; i<listSize; i++){
            Calendar calendar = new Calendar();
            LeadarCalendarDto leaderCalenar = leadarCalendararList.get(i);
            String title = leaderCalenar.getTitle();
            if(StringUtils.isEmpty(title)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，标题不能为空！");
            }

            if(title.length()>200){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，标题长度不能超过200个字符");
            }

//            if(!pattern.matcher(title).matches()){
//                return OperationResult.buildFailureResult("第"+(i+1)+"行，标题请输入中文/字母/数字/符号");
//            }

            calendar.setTitle(title);

            String calendarOwner = leaderCalenar.getCalendarOwner();
            if(StringUtils.isEmpty(calendarOwner)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，相关领导不能为空！");
            }

            String owner =canEditLeaderMap.get(calendarOwner);
            if(StringUtils.isEmpty(owner)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，无当前领导新增权限！");
            }

            calendar.setCalendarOwner(StringUtils.null2String(owner));

            String category = leaderCalenar.getCategory();
            if(StringUtils.isEmpty(category)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，所属分类不能为空！");
            }
            if("工作日程".equals(category)){
                List<Map> list = calendarCategoryService.ifSingleWork(owner);
                String categoryId = null;
                //如果已经有自定义的工作日程，直接取id
                if(CollectionUtils.isNotEmpty(list)) {
                    categoryId = list.get(0).get("id").toString();
                }else {//如果没有自定义工作日程，则新建一个自定义的工作日程
                    CalendarCategory ca = new CalendarCategory();
                    String newCategoryId = UuidUtils.UUID();
                    ca.setId(newCategoryId);
                    ca.setCreatedBy(owner);
                    ca.setCode("singleWork");
                    ca.setBackColor("#548dd4");
                    ca.setCategory("calendarOwner");
                    ca.setName("工作日程");
                    ca.setSortNo(0);
                    categoryId = ca.getId();
                    //保存类别
                    this.calendarCategoryService.save(ca);
                }
                calendar.setCalendarCategory(categoryId);
            }else{
                /** 非工作日程 **/
                CalendarCategory calendarCategory = calendarCategoryDao.getLeaderCalendarCate(owner,corpId,category);
                if(calendarCategory==null || calendarCategory.getId()==null){
                    return OperationResult.buildFailureResult("第"+(i+1)+"行，所属分类不存在!");
                }
                calendar.setCalendarCategory(calendarCategory.getId());
            }

            String participant = leaderCalenar.getParticipant();
            String part = UuidUtils.UUID();
            String partJson = "";
            if(StringUtils.isNotEmpty(participant)){
                List<String> paramList =  Arrays.asList(participant.split(","));
                List<Map> partUserList = this.getUserByLoginNames(paramList);
                if(CollectionUtils.isEmpty(partUserList) || partUserList.size()!=paramList.size()){
                    return OperationResult.buildFailureResult("第"+(i+1)+"行，部分参与人不存在!");
                }
                partJson = "[";
                for(Map partUser : partUserList){
                    partJson = partJson+"{\"scopeName\":\""+partUser.get("userName")+"\",\"scopeType\":\"user\",\"scopeValue\":\""+partUser.get("id")+"\",\"title\":\""+partUser.get("userName")+"\"},";
                }
                if(partJson.length()>10) {
                    partJson = partJson.substring(0, partJson.length()-1);
                }
                partJson = partJson+"]";
            }
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, partJson, "oa_calendar", "participant");

            calendar.setParticipant(part);

            String startDateStr = leaderCalenar.getStartDate();
            if(StringUtils.isEmpty(startDateStr)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，开始时间不能为空！");
            }

            String endDateStr = leaderCalenar.getEndDate();
            if(StringUtils.isEmpty(endDateStr)){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，结束时间不能为空！");
            }


            Date startDate = null;
            Date endDate = null;

            try {
                startDate = sdf.parse(startDateStr);
            } catch (ParseException e) {
                LOG.error("时间格式错误",e);
                return OperationResult.buildFailureResult("第"+(i+1)+"行，开始时间格式错误！");
            }

            try {
                endDate = sdf.parse(endDateStr);
            } catch (ParseException e) {
                LOG.error("时间格式错误",e);
                return OperationResult.buildFailureResult("第"+(i+1)+"行，结束时间格式错误！");
            }


            if(startDate.getTime()>=endDate.getTime()){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，开始时间不能大于、等于结束时间！");
            }

            generalCalendar.setTime(startDate);
            int hourBegin = generalCalendar.get(java.util.Calendar.HOUR_OF_DAY);
            int minuteBegin = generalCalendar.get(java.util.Calendar.MINUTE);
            int secondBegin = hourBegin*60*60+minuteBegin*60;
            calendar.setStartDate(startDate);
            if("1".equals(leaderTimeSettingType)){
                calendar.setEndDate(startDate);
                if(secondBegin>43200){
                    calendar.setStartTime(50400);
                    calendar.setEndTime(64800);
                    calendar.setSetTimeFlag("0");
                }else{
                    calendar.setStartTime(32400);
                    calendar.setEndTime(43200);
                    calendar.setSetTimeFlag("1");
                }
            }else{
                calendar.setStartTime(secondBegin);
                generalCalendar.setTime(endDate);
                int hourEnd = generalCalendar.get(java.util.Calendar.HOUR_OF_DAY);
                int minuteEnd = generalCalendar.get(java.util.Calendar.MINUTE);
                int secondEnd = hourEnd*60*60+minuteEnd*60;
                calendar.setEndTime(secondEnd);
                calendar.setEndDate(endDate);
            }


            String content = leaderCalenar.getContent();

            if(StringUtils.isNotEmpty(content) && content.length()>200){
                return OperationResult.buildFailureResult("第"+(i+1)+"行，内容长度不能超过200个字符");
            }

//            if(StringUtils.isNotEmpty(content) && !pattern.matcher(content).matches()){
//                return OperationResult.buildFailureResult("第"+(i+1)+"行，内容请输入中文/字母/数字/符号");
//            }

            calendar.setContent(content);

            calendar.setRemindStyle(remindStyle);
            calendar.setDuplicateType("no");
            calendar.setDuplicateEndType("always");
            calendar.setIsMain("1");
            calendar.setCreatedBy(userId);
            calendar.setDegreeOfImportance("1");//重要程度
            calendar.setExpiryReminder("yes");
            calendar.setExpiryReminderTime("10min");
            calendar.setIsAllDay("0");
            String viewer = UuidUtils.UUID();
            calendar.setViewer(viewer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, "", "oa_calendar", "viewer");
            String maintainer = UuidUtils.UUID();
            calendar.setMaintainer(maintainer);
            this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, "", "oa_calendar", "maintainer");

            calendarList.add(calendar);

        }
        super.save(calendarList);

        return OperationResult.buildSuccessResult("导入成功！");
    }

    /**
     * 对列表进行操作，以登录名作为key
     *
     */
    public Map<String,String> getCanEditLeaderMap(List<Map> canEditLeaderList){
        Map<String,String> canEditLeaderMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(canEditLeaderList)){
            for(Map canEditLeader : canEditLeaderList){
                canEditLeaderMap.put(StringUtils.null2String(canEditLeader.get("loginName")),StringUtils.null2String(canEditLeader.get("id")));
            }
        }
        return canEditLeaderMap;
    }

    /**
     * 根据登录名获取用户id列表
     *
     */
    public List<Map> getUserByLoginNames(List<String> loginNameList){
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT id,user_name as userName FROM sys_user WHERE login_name in (:loginNameList) ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("loginNameList",loginNameList);

        List<Map> list = findByListNativeQuery(sql.toString(),"",paramMap);
        return list;
    }

    /**
     * 获取日程默认提醒方式
     *
     *
     */
    public String getCalendarRemind(String corpId, String token){
        Map<String, Object> appInfo = configService.getAppInfoByAppCode("calendar",corpId,token);
        //获取系统后台的消息设置(wxWork,ding,evoPortal)
        String reminderAction = "" ;
        String openReminderAction = "" ;
        if(MapUtils.isNotEmpty(appInfo)) {
            //提醒方式
            reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
            //默认启用
            openReminderAction = StringUtils.null2String(appInfo.get("openReminderAction"));
        }
        String sms = StringUtils.equals(getSysParamValueByMark(corpId, token, "sysSMSsetting"), "1") && reminderAction.contains("sms") ? "1" : "0";
        String mobile = getSysParamValueByMark(corpId,token , "sysImType");
        //获取默认启用的提醒方式 移动端、短信
        String openMobile = openReminderAction.contains("mobile") ? "1":"0";
        String openSms = openReminderAction.contains("sms") ? "1":"0";
        String ifMobile = "0";
        if((mobile.contains("wxWork") || mobile.contains("ding") || mobile.contains("evoPortal") || mobile.contains("cocall") || mobile.contains("gding"))  && reminderAction.contains("mobile") ) {
            ifMobile = "1";
        }
        String remindStyle = "";
        if("1".equals(openMobile) && "1".equals(ifMobile)) {
            remindStyle = "mobile";
        }
        if("1".equals(openSms) && "1".equals(sms)) {
            if(remindStyle.length()>1) {
                remindStyle = remindStyle+",sms";
            }else {
                remindStyle = "sms";
            }
        }

        return remindStyle;
    }

    /**
     * 获取三方编码信息
     *
     *
     */
    public boolean getUmcIsOpen(String moduleCode,String corpId, String token){
        boolean flag = true;
        //根据code获取消息信息s
        Map<String, String> paramsMap = new HashMap();
        paramsMap.put("moduleCode", moduleCode);
        paramsMap.put("corpId",corpId);
        //String retJson = restBaseClient.get("/system/umc/module/getAllModuleInfo", token, paramsMap);
        String retJson = umcApiService.getAllModuleInfo(paramsMap, token);
        if (StringUtils.isNotBlank(retJson)) {
            Map<String, Object> resultMap = JsonUtils.readValue(retJson);
            if("0".equals(resultMap.get("code"))){
                String dataStr = StringUtils.null2String(resultMap.get("data"));
                if(StringUtils.isNotEmpty(dataStr)){
                    List<Map> dataList = (List<Map>) resultMap.get("data");
                    if(CollectionUtils.isNotEmpty(dataList)){
                        if(!"1".equals(StringUtils.null2String(dataList.get(0).get("is_enable")))){
                            flag = false;
                        }
                    }else{
                        flag = false;
                    }
                }else{
                    flag = false;
                }
            }else{
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 根据用户id获取该用户所属的个人群组id
     * @param userId 用户id
     * @param token 身份令牌
     * @return List<String> 个人群组列表
     *
     */
    public List<String> getGroupIdList(String userId, String token){
        //获取个人群组
        Map<String, String> params = new HashMap<>();
        params.put("userId",userId);
        String groupStr = pscGroupApiService.getPerGrpId(token,params);
        List<String> groupList = new ArrayList<>();
        try {
            Map<String, Object> dataMap = JsonUtils.readValue(groupStr);
            groupList = (List<String>) dataMap.get("data");
            if(groupList == null){
                groupList = new ArrayList<>();
            }
        }catch (Exception e){
            LOG.error("获取群组信息失败");
        }
        return groupList;
    }
    //gaoyw  获取辽政通临时token
    private  String getAccessToken(){//获取临时token
        String appid= GlobalConstant.getConfig("app.lzt.appid");
        String key=GlobalConstant.getConfig("app.lzt.key");
        String getTokenUrl=GlobalConstant.getConfig("app.lzt.url")+"/api/oauth/getAccessToken";
        String result="";
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("appId",appid);
        hashMap.put("secretKey",key);
        String reqJson=JSONObject.toJSONString(hashMap);
        try {
            Map<String,Object> headers = new HashMap<String,Object>();
            result= HttpsUtil.HttpsPostUtil(getTokenUrl, reqJson, "JSON");
            // System.out.println(result);
            Map obj= (JSONObject) JSONObject.parse(result);
            if("200".equals(obj.get("code")+"")){

                String rdata=obj.get("data")+"";
                Map data= (Map) JSONObject.parse(rdata);
                result=data.get("access_token")+"";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}


